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 <shenhaichen@gmail.com>
This commit is contained in:
maskpp 2023-08-24 19:59:29 +08:00 committed by GitHub
parent e93930d6ba
commit eb79758c01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 1 deletions

View file

@ -54,6 +54,11 @@ func NewClient(c *rpc.Client) *Client {
return &Client{c} 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() { func (ec *Client) Close() {
ec.c.Close() ec.c.Close()
} }

View file

@ -18,6 +18,8 @@ package rpc
import ( import (
"bytes" "bytes"
"compress/gzip"
"compress/zlib"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@ -27,6 +29,7 @@ import (
"mime" "mime"
"net/http" "net/http"
"net/url" "net/url"
"strings"
"sync" "sync"
"time" "time"
) )
@ -198,7 +201,9 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos
Body: body, 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. // httpServerConn turns a HTTP connection into a Conn.
@ -208,6 +213,28 @@ type httpServerConn struct {
r *http.Request 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 { func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
body := io.LimitReader(r.Body, maxRequestContentLength) body := io.LimitReader(r.Body, maxRequestContentLength)
conn := &httpServerConn{Reader: body, Writer: w, r: r} conn := &httpServerConn{Reader: body, Writer: w, r: r}