jx/internal/transport/transport.go

73 lines
1.3 KiB
Go
Raw Normal View History

2024-05-12 08:20:51 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package transport
import (
_ "errors"
"fmt"
"net/url"
"net/http"
_ "strings"
"path/filepath"
"io"
"os"
)
type Reader struct {
uri *url.URL
handle any
stream io.ReadCloser
}
func NewReader(u *url.URL) (*Reader, error) {
var e error
r := &Reader{ uri: u }
switch u.Scheme {
case "http", "https":
resp, err := http.Get(u.String())
r.handle = resp
r.stream = resp.Body
e = err
case "file":
fallthrough
default:
path := filepath.Join(u.Hostname(), u.RequestURI())
file, err := os.Open(path)
r.handle = file
r.stream = file
e = err
}
return r, e
}
type Writer struct {
}
func NewWriter(url *url.URL) (*Writer, error) {
return nil, nil
}
func (r *Reader) Read(b []byte) (int, error) {
return r.stream.Read(b)
}
func (r *Reader) Close() error {
return r.stream.Close()
}
func (r *Reader) Signature() string {
documentSignature := r.handle.(*http.Response).Header.Get("Signature")
if documentSignature == "" {
signatureResp, signatureErr := http.Get(fmt.Sprintf("%s.sig", r.uri.String()))
if signatureErr == nil {
defer signatureResp.Body.Close()
readSignatureBody, readSignatureErr := io.ReadAll(signatureResp.Body)
if readSignatureErr == nil {
documentSignature = string(readSignatureBody)
}
}
}
return documentSignature
}