Skip to content

Commit eb79758

Browse files
mask-ppicemelon
andauthored
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>
1 parent e93930d commit eb79758

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

ethclient/ethclient.go

+5
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ func NewClient(c *rpc.Client) *Client {
5454
return &Client{c}
5555
}
5656

57+
// SetHeader expose the function, in able to set http header.
58+
func (ec *Client) SetHeader(key, value string) {
59+
ec.c.SetHeader(key, value)
60+
}
61+
5762
func (ec *Client) Close() {
5863
ec.c.Close()
5964
}

rpc/http.go

+28-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package rpc
1818

1919
import (
2020
"bytes"
21+
"compress/gzip"
22+
"compress/zlib"
2123
"context"
2224
"encoding/json"
2325
"errors"
@@ -27,6 +29,7 @@ import (
2729
"mime"
2830
"net/http"
2931
"net/url"
32+
"strings"
3033
"sync"
3134
"time"
3235
)
@@ -198,7 +201,9 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos
198201
Body: body,
199202
}
200203
}
201-
return resp.Body, nil
204+
205+
// if encoding is set use it.
206+
return newDecodeCompression(resp.Header.Get("Content-Encoding"), resp.Body)
202207
}
203208

204209
// httpServerConn turns a HTTP connection into a Conn.
@@ -208,6 +213,28 @@ type httpServerConn struct {
208213
r *http.Request
209214
}
210215

216+
func newDecodeCompression(decoding string, rc io.ReadCloser) (io.ReadCloser, error) {
217+
tps := strings.Split(strings.TrimSpace(strings.ToLower(decoding)), ",")
218+
var res io.ReadCloser
219+
switch tps[0] {
220+
case "gzip":
221+
gz, err := gzip.NewReader(rc)
222+
if err != nil {
223+
return nil, err
224+
}
225+
res = gz
226+
case "deflate":
227+
zl, err := zlib.NewReader(rc)
228+
if err != nil {
229+
return nil, err
230+
}
231+
res = zl
232+
default:
233+
res = rc
234+
}
235+
return res, nil
236+
}
237+
211238
func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
212239
body := io.LimitReader(r.Body, maxRequestContentLength)
213240
conn := &httpServerConn{Reader: body, Writer: w, r: r}

0 commit comments

Comments
 (0)