123 lines
2.4 KiB
Go
123 lines
2.4 KiB
Go
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
|
|
package transport
|
|
|
|
import (
|
|
_ "errors"
|
|
"io"
|
|
_ "os"
|
|
"net/url"
|
|
"net/http"
|
|
"strings"
|
|
"fmt"
|
|
"bytes"
|
|
"context"
|
|
"path/filepath"
|
|
)
|
|
|
|
type BufferCloser struct {
|
|
stream io.Closer
|
|
*bytes.Buffer
|
|
}
|
|
|
|
type HTTP struct {
|
|
uri *url.URL
|
|
path string
|
|
exttype string
|
|
fileext string
|
|
buffer BufferCloser
|
|
getRequest *http.Request
|
|
getResponse *http.Response
|
|
postRequest *http.Request
|
|
postResponse *http.Response
|
|
Client *http.Client
|
|
}
|
|
|
|
func (b BufferCloser) Close() error {
|
|
if b.stream != nil {
|
|
return b.stream.Close()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func NewHTTP(u *url.URL, ctx context.Context) (h *HTTP, err error) {
|
|
h = &HTTP {
|
|
uri: u,
|
|
path: filepath.Join(u.Hostname(), u.RequestURI()),
|
|
Client: http.DefaultClient,
|
|
}
|
|
h.extension()
|
|
|
|
h.postRequest, err = http.NewRequestWithContext(ctx, "POST", u.String(), h.buffer)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.getRequest, err = http.NewRequestWithContext(ctx, "GET", u.String(), nil)
|
|
return
|
|
}
|
|
|
|
func (h *HTTP) extension() {
|
|
elements := strings.Split(h.path, ".")
|
|
numberOfElements := len(elements)
|
|
if numberOfElements > 2 {
|
|
h.exttype = elements[numberOfElements - 2]
|
|
h.fileext = elements[numberOfElements - 1]
|
|
}
|
|
h.exttype = elements[numberOfElements - 1]
|
|
}
|
|
|
|
func (h *HTTP) URI() *url.URL {
|
|
return h.uri
|
|
}
|
|
|
|
func (h *HTTP) Path() string {
|
|
return h.path
|
|
}
|
|
|
|
func (h *HTTP) Signature() (documentSignature string) {
|
|
if h.getResponse != nil {
|
|
documentSignature = h.getResponse.Header.Get("Signature")
|
|
if documentSignature == "" {
|
|
signatureResp, signatureErr := h.Client.Get(fmt.Sprintf("%s.sig", h.uri.String()))
|
|
if signatureErr == nil {
|
|
defer signatureResp.Body.Close()
|
|
readSignatureBody, readSignatureErr := io.ReadAll(signatureResp.Body)
|
|
if readSignatureErr == nil {
|
|
documentSignature = string(readSignatureBody)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return documentSignature
|
|
}
|
|
|
|
func (h *HTTP) ContentType() (contenttype string) {
|
|
contenttype = h.getResponse.Header.Get("Content-Type")
|
|
switch contenttype {
|
|
case "application/octet-stream":
|
|
return h.exttype
|
|
default:
|
|
}
|
|
return
|
|
}
|
|
|
|
func (h *HTTP) Gzip() bool {
|
|
return h.fileext == "gz"
|
|
}
|
|
|
|
func (h *HTTP) Reader() io.ReadCloser {
|
|
var err error
|
|
if h.getResponse, err = h.Client.Do(h.getRequest); err != nil {
|
|
panic(err)
|
|
}
|
|
return h.getResponse.Body
|
|
}
|
|
|
|
func (h *HTTP) Writer() io.WriteCloser {
|
|
var err error
|
|
if h.postResponse, err = h.Client.Do(h.postRequest); err != nil {
|
|
panic(err)
|
|
}
|
|
return h.buffer
|
|
}
|