Skip to content

Commit

Permalink
feat(sdk): support compressed response (#469)
Browse files Browse the repository at this point in the history
* enable use compression algorithm

* fix ci

* Just enable decode compressed content at ethclient

* fix comments

---------

Co-authored-by: Haichen Shen <shenhaichen@gmail.com>
  • Loading branch information
mask-pp and icemelon committed Aug 24, 2023
1 parent e93930d commit eb79758
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 5 additions & 0 deletions ethclient/ethclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
29 changes: 28 additions & 1 deletion rpc/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package rpc

import (
"bytes"
"compress/gzip"
"compress/zlib"
"context"
"encoding/json"
"errors"
Expand All @@ -27,6 +29,7 @@ import (
"mime"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
Expand Down Expand Up @@ -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.
Expand All @@ -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}
Expand Down

0 comments on commit eb79758

Please sign in to comment.