forked from bytedance/go-tagexpr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
body.go
108 lines (98 loc) · 2.01 KB
/
body.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package binding
import (
"bytes"
"compress/flate"
"compress/gzip"
"compress/zlib"
"errors"
"io"
"net/http"
"strings"
"google.golang.org/protobuf/proto"
)
func getBodyCodec(req Request) codec {
ct := req.GetContentType()
idx := strings.Index(ct, ";")
if idx != -1 {
ct = strings.TrimRight(ct[:idx], " ")
}
switch ct {
case "application/json":
return bodyJSON
case "application/x-protobuf":
return bodyProtobuf
case "application/x-www-form-urlencoded", "multipart/form-data":
return bodyForm
default:
return bodyUnsupport
}
}
// Body body copy
type Body struct {
*bytes.Buffer
bodyBytes []byte
}
// Close close.
func (b *Body) Close() error {
b.Buffer = nil
b.bodyBytes = nil
return nil
}
// Reset zero offset.
func (b *Body) Reset() {
b.Buffer = bytes.NewBuffer(b.bodyBytes)
}
// Bytes returns all of the body bytes.
func (b *Body) Bytes() []byte {
return b.bodyBytes
}
// Len returns all of the body length.
func (b *Body) Len() int {
return len(b.bodyBytes)
}
// GetBody get the body from http.Request
func GetBody(r *http.Request) (*Body, error) {
switch body := r.Body.(type) {
case *Body:
body.Reset()
return body, nil
default:
var err error
var closeBody = r.Body.Close
switch r.Header.Get("Content-Encoding") {
case "gzip":
var gzipReader *gzip.Reader
gzipReader, err = gzip.NewReader(r.Body)
if err == nil {
r.Body = gzipReader
}
case "deflate":
r.Body = flate.NewReader(r.Body)
case "zlib":
var readCloser io.ReadCloser
readCloser, err = zlib.NewReader(r.Body)
if err == nil {
r.Body = readCloser
}
}
if err != nil {
return nil, err
}
var buf bytes.Buffer
_, _ = io.Copy(&buf, r.Body)
_ = closeBody()
_body := &Body{
Buffer: &buf,
bodyBytes: buf.Bytes(),
}
r.Body = _body
return _body, nil
}
}
func bindProtobuf(pointer interface{}, bodyBytes []byte) error {
msg, ok := pointer.(proto.Message)
if !ok {
return errors.New("protobuf content type is not supported")
}
return proto.Unmarshal(bodyBytes, msg)
}