jx/internal/transport/readwriter.go

113 lines
2.4 KiB
Go
Raw Normal View History

// 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"
"context"
"io/fs"
)
type HandlerReadWriter interface {
ReadWriter() io.ReadWriteCloser
}
type ReadWriter struct {
uri *url.URL
handle Handler
stream io.ReadWriteCloser
exists func() bool
}
func NewReadWriter(u *url.URL) (readWriter *ReadWriter, e error) {
return NewReadWriterWithContext(u, context.Background())
}
func NewReadWriterWithContext(u *url.URL, ctx context.Context) (readWriter *ReadWriter, e error) {
readWriter = &ReadWriter{ uri: u }
switch u.Scheme {
case "http", "https":
readWriter.handle, e = NewHTTPReadWriter(u, ctx)
case "file":
fallthrough
default:
readWriter.handle, e = NewFile(u)
readWriter.exists = func() bool { return FileExists(u) }
}
readWriter.SetStream(readWriter.handle.(HandlerReadWriter).ReadWriter())
return
}
func NewReadWriterURI(uri string) (readWriter *ReadWriter, e error) {
var u *url.URL
if u, e = url.Parse(uri); e == nil {
return NewReadWriter(u)
}
return
}
func (r *ReadWriter) Exists() bool { return r.exists() }
func (r *ReadWriter) Read(b []byte) (int, error) {
return r.stream.Read(b)
}
func (r *ReadWriter) Close() error {
return r.stream.Close()
}
func (r *ReadWriter) ContentType() string {
return r.handle.ContentType()
}
func (r *ReadWriter) SetGzip(value bool) {
r.handle.SetGzip(value)
}
func (r *ReadWriter) Gzip() bool {
return r.handle.Gzip()
}
func (r *ReadWriter) Signature() string {
return r.handle.Signature()
}
func (r *ReadWriter) SetStream(s io.ReadWriteCloser) {
r.stream = s
}
func (r *ReadWriter) Write(b []byte) (int, error) {
return r.stream.Write(b)
}
func (r *ReadWriter) ReadFrom(reader io.Reader) (n int64, e error) {
return r.stream.(io.ReaderFrom).ReadFrom(reader)
}
func (r *ReadWriter) AddHeader(name string, value string) {
r.handle.(*HTTPReadWriter).PostRequest().Header.Add(name, value)
}
func (r *ReadWriter) Status() string {
return r.handle.(*HTTPReadWriter).PostResponse().Status
}
func (r *ReadWriter) StatusCode() int {
return r.handle.(*HTTPReadWriter).PostResponse().StatusCode
}
func (r *ReadWriter) Response() *http.Response {
return r.handle.(*HTTPReadWriter).PostResponse()
}
func (r *ReadWriter) Stat() (info fs.FileInfo, err error) {
return r.handle.Stat()
}