/
param_info.go
391 lines (365 loc) · 9.82 KB
/
param_info.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package binding
import (
jsonpkg "encoding/json"
"errors"
"reflect"
"strconv"
"strings"
"github.com/henrylee2cn/ameda"
"github.com/henrylee2cn/goutil"
"github.com/tidwall/gjson"
"github.com/valyala/fasthttp"
"github.com/bytedance/go-tagexpr"
)
const (
specialChar = "\x07"
)
type paramInfo struct {
fieldSelector string
structField reflect.StructField
tagInfos []*tagInfo
omitIns map[in]bool
bindErrFactory func(failField, msg string) error
looseZeroMode bool
defaultVal []byte
}
func (p *paramInfo) name(paramIn in) string {
var name string
for _, info := range p.tagInfos {
if info.paramIn == json {
name = info.paramName
break
}
}
if name == "" {
return p.structField.Name
}
return name
}
func (p *paramInfo) getField(expr *tagexpr.TagExpr, initZero bool) (reflect.Value, error) {
fh, found := expr.Field(p.fieldSelector)
if found {
v := fh.Value(initZero)
if v.IsValid() {
return v, nil
}
}
return reflect.Value{}, nil
}
func (p *paramInfo) bindRawBody(info *tagInfo, expr *tagexpr.TagExpr, bodyBytes []byte) error {
if len(bodyBytes) == 0 {
if info.required {
return info.requiredError
}
return nil
}
v, err := p.getField(expr, true)
if err != nil || !v.IsValid() {
return err
}
v = goutil.DereferenceValue(v)
switch v.Kind() {
case reflect.Slice:
if v.Type().Elem().Kind() != reflect.Uint8 {
return info.typeError
}
v.Set(reflect.ValueOf(bodyBytes))
return nil
case reflect.String:
v.Set(reflect.ValueOf(goutil.BytesToString(bodyBytes)))
return nil
default:
return info.typeError
}
}
func (p *paramInfo) bindPath(info *tagInfo, expr *tagexpr.TagExpr, req *fasthttp.RequestCtx) (bool, error) {
r, found := req.UserValue(info.paramName).(string)
if !found {
if info.required {
return false, info.requiredError
}
return false, nil
}
return true, p.bindStringSlice(info, expr, []string{r})
}
func (p *paramInfo) bindQuery(info *tagInfo, expr *tagexpr.TagExpr, queryValues *fasthttp.Args) (bool, error) {
return p.bindMapStrings(info, expr, queryValues)
}
func (p *paramInfo) bindHeader(info *tagInfo, expr *tagexpr.TagExpr, reqHeader *fasthttp.RequestHeader) (bool, error) {
r := reqHeader.Peek(info.paramName)
if len(r) == 0 {
if info.required {
return false, info.requiredError
}
return false, nil
}
return true, p.bindStringSlice(info, expr, []string{ameda.UnsafeBytesToString(r)})
}
func (p *paramInfo) bindCookie(info *tagInfo, expr *tagexpr.TagExpr, reqHeader *fasthttp.RequestHeader) error {
r := reqHeader.Cookie(info.paramName)
if len(r) == 0 {
if info.required {
return info.requiredError
}
return nil
}
return p.bindStringSlice(info, expr, []string{ameda.UnsafeBytesToString(r)})
}
func (p *paramInfo) bindOrRequireBody(info *tagInfo, expr *tagexpr.TagExpr, bodyCodec codec, bodyString string, postForm *fasthttp.Args) (bool, error) {
switch bodyCodec {
case bodyForm:
return p.bindMapStrings(info, expr, postForm)
case bodyJSON:
return p.checkRequireJSON(info, expr, bodyString, false)
case bodyProtobuf:
err := p.checkRequireProtobuf(info, expr, false)
return err == nil, err
default:
return false, info.contentTypeError
}
}
func (p *paramInfo) checkRequireProtobuf(info *tagInfo, expr *tagexpr.TagExpr, checkOpt bool) error {
if checkOpt && !info.required {
v, err := p.getField(expr, false)
if err != nil || !v.IsValid() {
return info.requiredError
}
}
return nil
}
func (p *paramInfo) checkRequireJSON(info *tagInfo, expr *tagexpr.TagExpr, bodyString string, checkOpt bool) (bool, error) {
var requiredError error
if checkOpt || info.required { // only return error if it's a required field
requiredError = info.requiredError
}
if !gjson.Get(bodyString, info.namePath).Exists() {
idx := strings.LastIndex(info.namePath, ".")
// There should be a superior but it is empty, no error is reported
if idx > 0 && !gjson.Get(bodyString, info.namePath[:idx]).Exists() {
return true, nil
}
return false, requiredError
}
v, err := p.getField(expr, false)
if err != nil || !v.IsValid() {
return false, requiredError
}
return true, nil
}
func (p *paramInfo) bindMapStrings(info *tagInfo, expr *tagexpr.TagExpr, values *fasthttp.Args) (bool, error) {
r := values.PeekMulti(info.paramName)
if len(r) == 0 {
if info.required {
return false, info.requiredError
}
return false, nil
}
return true, p.bindStringSlice(info, expr, bytesSliceToStringSlice(r))
}
func bytesSliceToStringSlice(bs [][]byte) []string {
a := make([]string, len(bs))
for i, b := range bs {
a[i] = ameda.UnsafeBytesToString(b)
}
return a
}
// NOTE: len(a)>0
func (p *paramInfo) bindStringSlice(info *tagInfo, expr *tagexpr.TagExpr, a []string) error {
v, err := p.getField(expr, true)
if err != nil || !v.IsValid() {
return err
}
v = goutil.DereferenceValue(v)
switch v.Kind() {
case reflect.String:
v.SetString(a[0])
return nil
case reflect.Bool:
var bol bool
bol, err = strconv.ParseBool(a[0])
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetBool(bol)
return nil
}
case reflect.Float32:
var f float64
f, err = strconv.ParseFloat(a[0], 32)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetFloat(f)
return nil
}
case reflect.Float64:
var f float64
f, err = strconv.ParseFloat(a[0], 64)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetFloat(f)
return nil
}
case reflect.Int64, reflect.Int:
var i int64
i, err = strconv.ParseInt(a[0], 10, 64)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetInt(i)
return nil
}
case reflect.Int32:
var i int64
i, err = strconv.ParseInt(a[0], 10, 32)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetInt(i)
return nil
}
case reflect.Int16:
var i int64
i, err = strconv.ParseInt(a[0], 10, 16)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetInt(i)
return nil
}
case reflect.Int8:
var i int64
i, err = strconv.ParseInt(a[0], 10, 8)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetInt(i)
return nil
}
case reflect.Uint64, reflect.Uint:
var u uint64
u, err = strconv.ParseUint(a[0], 10, 64)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetUint(u)
return nil
}
case reflect.Uint32:
var u uint64
u, err = strconv.ParseUint(a[0], 10, 32)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetUint(u)
return nil
}
case reflect.Uint16:
var u uint64
u, err = strconv.ParseUint(a[0], 10, 16)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetUint(u)
return nil
}
case reflect.Uint8:
var u uint64
u, err = strconv.ParseUint(a[0], 10, 8)
if err == nil || (a[0] == "" && p.looseZeroMode) {
v.SetUint(u)
return nil
}
case reflect.Slice:
vv, err := stringsToValue(v.Type().Elem(), a, p.looseZeroMode)
if err == nil {
v.Set(vv)
return nil
}
fallthrough
default:
fn := typeUnmarshalFuncs[v.Type()]
if fn != nil {
vv, err := fn(a[0], p.looseZeroMode)
if err == nil {
v.Set(vv)
return nil
}
}
}
return info.typeError
}
func (p *paramInfo) bindDefaultVal(expr *tagexpr.TagExpr, defaultValue []byte) (bool, error) {
if defaultValue == nil {
return false, nil
}
v, err := p.getField(expr, true)
if err != nil || !v.IsValid() {
return false, err
}
return true, jsonpkg.Unmarshal(defaultValue, v.Addr().Interface())
}
// setDefaultVal preprocess the default tags and store the parsed value
func (p *paramInfo) setDefaultVal() error {
for _, info := range p.tagInfos {
if info.paramIn != default_val {
continue
}
defaultVal := info.paramName
st := ameda.DereferenceType(p.structField.Type)
switch st.Kind() {
case reflect.String:
p.defaultVal, _ = jsonpkg.Marshal(defaultVal)
continue
case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct:
// escape single quote and double quote, replace single quote with double quote
defaultVal = strings.Replace(defaultVal, `"`, `\"`, -1)
defaultVal = strings.Replace(defaultVal, `\'`, specialChar, -1)
defaultVal = strings.Replace(defaultVal, `'`, `"`, -1)
defaultVal = strings.Replace(defaultVal, specialChar, `'`, -1)
}
p.defaultVal = ameda.UnsafeStringToBytes(defaultVal)
}
return nil
}
var errMismatch = errors.New("type mismatch")
func stringsToValue(t reflect.Type, a []string, emptyAsZero bool) (reflect.Value, error) {
var i interface{}
var err error
var ptrDepth int
elemKind := t.Kind()
for elemKind == reflect.Ptr {
t = t.Elem()
elemKind = t.Kind()
ptrDepth++
}
switch elemKind {
case reflect.String:
i = a
case reflect.Bool:
i, err = goutil.StringsToBools(a, emptyAsZero)
case reflect.Float32:
i, err = goutil.StringsToFloat32s(a, emptyAsZero)
case reflect.Float64:
i, err = goutil.StringsToFloat64s(a, emptyAsZero)
case reflect.Int:
i, err = goutil.StringsToInts(a, emptyAsZero)
case reflect.Int64:
i, err = goutil.StringsToInt64s(a, emptyAsZero)
case reflect.Int32:
i, err = goutil.StringsToInt32s(a, emptyAsZero)
case reflect.Int16:
i, err = goutil.StringsToInt16s(a, emptyAsZero)
case reflect.Int8:
i, err = goutil.StringsToInt8s(a, emptyAsZero)
case reflect.Uint:
i, err = goutil.StringsToUints(a, emptyAsZero)
case reflect.Uint64:
i, err = goutil.StringsToUint64s(a, emptyAsZero)
case reflect.Uint32:
i, err = goutil.StringsToUint32s(a, emptyAsZero)
case reflect.Uint16:
i, err = goutil.StringsToUint16s(a, emptyAsZero)
case reflect.Uint8:
i, err = goutil.StringsToUint8s(a, emptyAsZero)
default:
fn := typeUnmarshalFuncs[t]
if fn == nil {
return reflect.Value{}, errMismatch
}
v := reflect.New(reflect.SliceOf(t)).Elem()
for _, s := range a {
vv, err := fn(s, emptyAsZero)
if err != nil {
return reflect.Value{}, errMismatch
}
v = reflect.Append(v, vv)
}
return goutil.ReferenceSlice(v, ptrDepth), nil
}
if err != nil {
return reflect.Value{}, errMismatch
}
return goutil.ReferenceSlice(reflect.ValueOf(i), ptrDepth), nil
}