Skip to content

Commit 3c3e845

Browse files
committed
chore(binding): support Content-Encoding
Change-Id: I8ff72eb62108bcd5a7418e434d87cbe03a8fbf37
1 parent 3b2f67b commit 3c3e845

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

binding/body.go

+24-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ package binding
22

33
import (
44
"bytes"
5+
"compress/flate"
6+
"compress/gzip"
7+
"compress/zlib"
58
jsonpkg "encoding/json"
69
"errors"
710
"io"
@@ -60,12 +63,30 @@ func GetBody(r *http.Request) (*Body, error) {
6063
body.Reset()
6164
return body, nil
6265
default:
63-
var buf bytes.Buffer
64-
_, err := io.Copy(&buf, r.Body)
65-
r.Body.Close()
66+
var err error
67+
var closeBody = r.Body.Close
68+
switch r.Header.Get("Content-Encoding") {
69+
case "gzip":
70+
var gzipReader *gzip.Reader
71+
gzipReader, err = gzip.NewReader(r.Body)
72+
if err == nil {
73+
r.Body = gzipReader
74+
}
75+
case "deflate":
76+
r.Body = flate.NewReader(r.Body)
77+
case "zlib":
78+
var readCloser io.ReadCloser
79+
readCloser, err = zlib.NewReader(r.Body)
80+
if err == nil {
81+
r.Body = readCloser
82+
}
83+
}
6684
if err != nil {
6785
return nil, err
6886
}
87+
var buf bytes.Buffer
88+
_, _ = io.Copy(&buf, r.Body)
89+
_ = closeBody()
6990
_body := &Body{
7091
Buffer: &buf,
7192
bodyBytes: buf.Bytes(),

binding/body_test.go

+16-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package binding
22

33
import (
44
"bytes"
5+
"compress/gzip"
56
"io/ioutil"
67
"net/http"
78
"testing"
@@ -10,11 +11,25 @@ import (
1011
)
1112

1213
func TestBody(t *testing.T) {
14+
const USE_GZIP = true
1315
var buf bytes.Buffer
14-
buf.WriteString("abc")
16+
if USE_GZIP {
17+
w := gzip.NewWriter(&buf)
18+
_, err := w.Write([]byte("abc"))
19+
assert.NoError(t, err)
20+
err = w.Flush()
21+
assert.NoError(t, err)
22+
} else {
23+
buf.WriteString("abc")
24+
}
1525
req := &http.Request{
1626
Body: ioutil.NopCloser(&buf),
1727
}
28+
if USE_GZIP {
29+
req.Header = map[string][]string{
30+
"Content-Encoding": []string{"gzip"},
31+
}
32+
}
1833
body, err := GetBody(req)
1934
assert.NoError(t, err)
2035
b, err := ioutil.ReadAll(body)

0 commit comments

Comments
 (0)