/
bind.go
298 lines (261 loc) · 6.61 KB
/
bind.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package binding
import (
"net/http"
"reflect"
_ "unsafe"
"github.com/bytedance/go-tagexpr"
"github.com/bytedance/go-tagexpr/validator"
"github.com/henrylee2cn/goutil"
"github.com/henrylee2cn/goutil/tpack"
)
// Level the level of handling tags
type Level uint8
const (
// OnlyFirst handle only the first level fields
OnlyFirst Level = iota
// FirstAndTagged handle the first level fields and all the tagged fields
FirstAndTagged
// Any handle any level fields
Any
)
// Binding binding and verification tool for http request
type Binding struct {
level Level
vd *validator.Validator
recvs goutil.Map
bindErrFactory func(failField, msg string) error
}
// New creates a binding tool.
// NOTE:
// If tagName=='', `api` is used
func New(tagName string) *Binding {
if tagName == "" {
tagName = "api"
}
b := &Binding{
vd: validator.New(tagName),
recvs: goutil.AtomicMap(),
}
return b.SetLevel(FirstAndTagged).SetErrorFactory(nil, nil)
}
// SetLevel set the level of handling tags.
// NOTE:
// default is First
func (b *Binding) SetLevel(level Level) *Binding {
switch level {
case OnlyFirst, FirstAndTagged, Any:
b.level = level
default:
b.level = FirstAndTagged
}
return b
}
var defaultValidatingErrFactory = newDefaultErrorFactory("invalid parameter")
var defaultBindErrFactory = newDefaultErrorFactory("binding failed")
// SetErrorFactory customizes the factory of validation error.
// NOTE:
// If errFactory==nil, the default is used
func (b *Binding) SetErrorFactory(bindErrFactory, validatingErrFactory func(failField, msg string) error) *Binding {
if bindErrFactory == nil {
bindErrFactory = defaultBindErrFactory
}
if validatingErrFactory == nil {
validatingErrFactory = defaultValidatingErrFactory
}
b.bindErrFactory = bindErrFactory
b.vd.SetErrorFactory(validatingErrFactory)
return b
}
// BindAndValidate binds the request parameters and validates them if needed.
func (b *Binding) BindAndValidate(structPointer interface{}, req *http.Request, pathParams PathParams) error {
v, err := b.structValueOf(structPointer)
if err != nil {
return err
}
hasVd, err := b.bind(v, req, pathParams)
if err != nil {
return err
}
if hasVd {
return b.vd.Validate(v)
}
return nil
}
// Bind binds the request parameters.
func (b *Binding) Bind(structPointer interface{}, req *http.Request, pathParams PathParams) error {
v, err := b.structValueOf(structPointer)
if err != nil {
return err
}
_, err = b.bind(v, req, pathParams)
return err
}
// Validate validates whether the fields of v is valid.
func (b *Binding) Validate(value interface{}) error {
return b.vd.Validate(value)
}
func (b *Binding) structValueOf(structPointer interface{}) (reflect.Value, error) {
v, ok := structPointer.(reflect.Value)
if !ok {
v = reflect.ValueOf(structPointer)
}
if v.Kind() != reflect.Ptr {
return v, b.bindErrFactory("", "structPointer must be a non-nil struct pointer")
}
v = derefValue(v)
if v.Kind() != reflect.Struct || !v.CanAddr() || !v.IsValid() {
return v, b.bindErrFactory("", "structPointer must be a non-nil struct pointer")
}
return v, nil
}
func (b *Binding) getObjOrPrepare(value reflect.Value) (*receiver, error) {
runtimeTypeID := tpack.From(value).RuntimeTypeID()
i, ok := b.recvs.Load(runtimeTypeID)
if ok {
return i.(*receiver), nil
}
expr, err := b.vd.VM().Run(reflect.New(value.Type()).Elem())
if err != nil {
return nil, err
}
var recv = &receiver{
params: make([]*paramInfo, 0, 16),
}
var errExprSelector tagexpr.ExprSelector
var errMsg string
expr.RangeFields(func(fh *tagexpr.FieldHandler) bool {
paths, name := fh.FieldSelector().Split()
var evals map[tagexpr.ExprSelector]func() interface{}
switch b.level {
case OnlyFirst:
if len(paths) > 0 {
return true
}
case FirstAndTagged:
if len(paths) > 0 {
var canHandle bool
evals = fh.EvalFuncs()
for es := range evals {
switch v := es.Name(); v {
case "raw_body", "body", "query", "path", "header", "cookie", "required":
canHandle = true
break
}
}
if !canHandle {
return true
}
}
default:
// Any
}
if !fh.Value(true).CanSet() {
selector := fh.StringSelector()
errMsg = "field cannot be set: " + selector
errExprSelector = tagexpr.ExprSelector(selector)
return false
}
in := auto
p := recv.getOrAddParam(fh, b.bindErrFactory)
if evals == nil {
evals = fh.EvalFuncs()
}
L:
for es, eval := range evals {
switch es.Name() {
case validator.MatchExprName:
recv.hasVd = true
continue L
case validator.ErrMsgExprName:
continue L
case "required":
p.required = tagexpr.FakeBool(eval())
continue L
case "raw_body":
recv.hasRawBody = true
in = raw_body
case "body":
recv.hasBody = true
in = body
case "query":
recv.hasQuery = true
in = query
case "path":
recv.hasPath = true
in = path
case "header":
in = header
case "cookie":
recv.hasCookie = true
in = cookie
default:
continue L
}
name, errMsg = getParamName(eval, name)
if errMsg != "" {
errExprSelector = es
return false
}
}
if in == auto {
recv.hasBody = true
recv.hasAuto = true
}
p.in = in
p.name = name
return true
})
if errMsg != "" {
return nil, b.bindErrFactory(errExprSelector.String(), errMsg)
}
recv.initParams()
b.recvs.Store(runtimeTypeID, recv)
return recv, nil
}
func (b *Binding) bind(value reflect.Value, req *http.Request, pathParams PathParams) (hasVd bool, err error) {
recv, err := b.getObjOrPrepare(value)
if err != nil {
return false, err
}
expr, err := b.vd.VM().Run(value)
if err != nil {
return false, err
}
bodyCodec := recv.getBodyCodec(req)
bodyBytes, err := recv.getBodyBytes(req, bodyCodec == jsonBody)
if err != nil {
return false, err
}
postForm, err := recv.getPostForm(req, bodyCodec == formBody)
if err != nil {
return false, err
}
queryValues := recv.getQuery(req)
cookies := recv.getCookies(req)
for _, param := range recv.params {
switch param.in {
case query:
_, err = param.bindQuery(expr, queryValues)
case path:
_, err = param.bindPath(expr, pathParams)
case header:
_, err = param.bindHeader(expr, req.Header)
case cookie:
err = param.bindCookie(expr, cookies)
case body:
_, err = param.bindBody(expr, bodyCodec, postForm, bodyBytes)
case raw_body:
err = param.bindRawBody(expr, bodyBytes)
default:
var found bool
found, err = param.bindBody(expr, bodyCodec, postForm, bodyBytes)
if !found {
_, err = param.bindQuery(expr, queryValues)
}
}
if err != nil {
return recv.hasVd, err
}
}
return recv.hasVd, nil
}