From eb79758c01745ab60a216d2ddef02e7d5b53d5ab Mon Sep 17 00:00:00 2001 From: maskpp Date: Thu, 24 Aug 2023 19:59:29 +0800 Subject: [PATCH] feat(sdk): support compressed response (#469) * enable use compression algorithm * fix ci * Just enable decode compressed content at ethclient * fix comments --------- Co-authored-by: Haichen Shen --- ethclient/ethclient.go | 5 +++++ rpc/http.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index f46aed9a735e..df7a7dd69a6c 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -54,6 +54,11 @@ func NewClient(c *rpc.Client) *Client { return &Client{c} } +// SetHeader expose the function, in able to set http header. +func (ec *Client) SetHeader(key, value string) { + ec.c.SetHeader(key, value) +} + func (ec *Client) Close() { ec.c.Close() } diff --git a/rpc/http.go b/rpc/http.go index 32f4e7d90a25..75aefb085846 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -18,6 +18,8 @@ package rpc import ( "bytes" + "compress/gzip" + "compress/zlib" "context" "encoding/json" "errors" @@ -27,6 +29,7 @@ import ( "mime" "net/http" "net/url" + "strings" "sync" "time" ) @@ -198,7 +201,9 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos Body: body, } } - return resp.Body, nil + + // if encoding is set use it. + return newDecodeCompression(resp.Header.Get("Content-Encoding"), resp.Body) } // httpServerConn turns a HTTP connection into a Conn. @@ -208,6 +213,28 @@ type httpServerConn struct { r *http.Request } +func newDecodeCompression(decoding string, rc io.ReadCloser) (io.ReadCloser, error) { + tps := strings.Split(strings.TrimSpace(strings.ToLower(decoding)), ",") + var res io.ReadCloser + switch tps[0] { + case "gzip": + gz, err := gzip.NewReader(rc) + if err != nil { + return nil, err + } + res = gz + case "deflate": + zl, err := zlib.NewReader(rc) + if err != nil { + return nil, err + } + res = zl + default: + res = rc + } + return res, nil +} + func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec { body := io.LimitReader(r.Body, maxRequestContentLength) conn := &httpServerConn{Reader: body, Writer: w, r: r}