2022-03-22 00:47:08 +03:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2022-03-22 01:03:13 +03:00
|
|
|
"io"
|
2022-03-22 00:47:08 +03:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"storj.io/drpc"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ drpc.Transport = &httpTransport{}
|
|
|
|
|
|
|
|
type httpTransport struct {
|
|
|
|
c *http.Client
|
|
|
|
method string
|
|
|
|
endpoint string
|
|
|
|
ct string
|
|
|
|
closed bool
|
2022-03-22 01:03:13 +03:00
|
|
|
body io.ReadCloser
|
2022-03-22 00:47:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
2022-03-22 01:03:13 +03:00
|
|
|
return t.body.Read(buf)
|
2022-03-22 00:47:08 +03:00
|
|
|
}
|
|
|
|
|
2022-03-22 01:03:13 +03:00
|
|
|
func (t *httpTransport) Write(buf []byte) (n int, err error) {
|
|
|
|
var req *http.Request
|
|
|
|
var rsp *http.Response
|
|
|
|
|
|
|
|
req, err = http.NewRequest(t.method, t.endpoint, bytes.NewReader(buf))
|
2022-03-22 00:47:08 +03:00
|
|
|
if err != nil {
|
2022-03-22 01:03:13 +03:00
|
|
|
return n, err
|
2022-03-22 00:47:08 +03:00
|
|
|
}
|
|
|
|
req.Header.Add("Content-Type", t.ct)
|
2022-03-22 01:03:13 +03:00
|
|
|
rsp, err = t.c.Do(req)
|
2022-03-22 00:47:08 +03:00
|
|
|
if err != nil {
|
2022-03-22 01:03:13 +03:00
|
|
|
return n, err
|
2022-03-22 00:47:08 +03:00
|
|
|
}
|
2022-03-22 01:03:13 +03:00
|
|
|
|
|
|
|
t.body = rsp.Body
|
2022-03-22 00:47:08 +03:00
|
|
|
return len(buf), err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *httpTransport) Close() error {
|
2022-03-22 01:03:13 +03:00
|
|
|
if t.body == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return t.body.Close()
|
2022-03-22 00:47:08 +03:00
|
|
|
}
|