From 43478edf9523a75d2b522d52ad167b27830d669c Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 22 Mar 2022 00:47:08 +0300 Subject: [PATCH] initial import Signed-off-by: Vasiliy Tolstov --- go.mod | 7 +++++++ go.sum | 10 ++++++++++ http.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 http.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e765a4c --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module github.com/unistack-org/drpc-transport-http + +go 1.17 + +require storj.io/drpc v0.0.30 + +require github.com/zeebo/errs v1.2.2 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..204b492 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/errs v1.2.2 h1:5NFypMTuSdoySVTqlNs1dEoU21QVamMQJxW/Fii5O7g= +github.com/zeebo/errs v1.2.2/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +storj.io/drpc v0.0.30 h1:jqPe4T9KEu3CDBI05A2hCMgMSHLtd/E0N0yTF9QreIE= +storj.io/drpc v0.0.30/go.mod h1:6rcOyR/QQkSTX/9L5ZGtlZaE2PtXTTZl8d+ulSeeYEg= diff --git a/http.go b/http.go new file mode 100644 index 0000000..8cab3ac --- /dev/null +++ b/http.go @@ -0,0 +1,58 @@ +package http + +import ( + "bytes" + "io/ioutil" + "net/http" + + "storj.io/drpc" +) + +var _ drpc.Transport = &httpTransport{} + +type httpTransport struct { + c *http.Client + method string + endpoint string + ct string + closed bool +} + +func NewTransport(c *http.Client, endpoint, method, ct string) *httpTransport { + if ct == "" { + ct = "application/drpc" + } + return &httpTransport{c: c, method: method, endpoint: endpoint, ct: ct} +} + +func (t *httpTransport) Read(buf []byte) (int, error) { + req, err := http.NewRequest(t.method, t.endpoint, nil) + if err != nil { + return 0, err + } + req.Header.Add("Content-Type", t.ct) + rsp, err := t.c.Do(req) + if err != nil { + return 0, err + } + buf, err = ioutil.ReadAll(rsp.Body) + return len(buf), err +} + +func (t *httpTransport) Write(buf []byte) (int, error) { + req, err := http.NewRequest(t.method, t.endpoint, bytes.NewReader(buf)) + if err != nil { + return 0, err + } + req.Header.Add("Content-Type", t.ct) + _, err = t.c.Do(req) + if err != nil { + return 0, err + } + return len(buf), err +} + +func (t *httpTransport) Close() error { + t.closed = true + return nil +}