forked from andeya/faygo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
param.go
389 lines (361 loc) · 9.15 KB
/
param.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
// Copyright 2016 HenryLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package apiware
import (
"errors"
"fmt"
"math"
"reflect"
"regexp"
"strconv"
"strings"
)
// some define
const (
TAG_PARAM = "param" // request param tag name
TAG_IGNORE_PARAM = "-" // ignore request param tag value
KEY_IN = "in" // position of param
KEY_NAME = "name" // specify request param`s name
KEY_REQUIRED = "required" // request param is required or not
KEY_DESC = "desc" // request param description
KEY_LEN = "len" // length range of param's value
KEY_RANGE = "range" // numerical range of param's value
KEY_NONZERO = "nonzero" // param`s value can not be zero
KEY_REGEXP = "regexp" // verify the value of the param with a regular expression(param value can not be null)
KEY_MAXMB = "maxmb" // when request Content-Type is multipart/form-data, the max memory for body.(multi-param, whichever is greater)
KEY_ERR = "err" // the custom error for binding or validating
MB = 1 << 20 // 1MB
defaultMaxMemory = 32 * MB // 32 MB
defaultMaxMemoryMB = 32
)
// ParseTags returns the key-value in the tag string.
// If the tag does not have the conventional format,
// the value returned by ParseTags is unspecified.
func ParseTags(tag string) map[string]string {
var values = map[string]string{}
for tag != "" {
// Skip leading space.
i := 0
for i < len(tag) && tag[i] != '<' {
i++
}
if i >= len(tag) || tag[i] != '<' {
break
}
i++
// Skip the left Spaces
for i < len(tag) && tag[i] == ' ' {
i++
}
if i >= len(tag) {
break
}
tag = tag[i:]
if tag == "" {
break
}
var name, value string
var hadName bool
i = 0
PAIR:
for i < len(tag) {
switch tag[i] {
case ':':
if hadName {
i++
continue
}
name = strings.TrimRight(tag[:i], " ")
tag = strings.TrimLeft(tag[i+1:], " ")
hadName = true
i = 0
case '\\':
i++
// Fix the escape character of `\\<` or `\\>`
if tag[i] == '<' || tag[i] == '>' {
tag = tag[:i-1] + tag[i:]
} else {
i++
}
case '>':
if !hadName {
name = strings.TrimRight(tag[:i], " ")
} else {
value = strings.TrimRight(tag[:i], " ")
}
values[name] = value
break PAIR
default:
i++
}
}
if i >= len(tag) {
break
}
tag = tag[i+1:]
}
return values
}
// Param use the struct field to define a request parameter model
type Param struct {
apiName string // ParamsAPI name
name string // param name
indexPath []int
isRequired bool // file is required or not
isFile bool // is file param or not
tags map[string]string // struct tags for this param
verifyFuncs []func(reflect.Value) error
rawTag reflect.StructTag // the raw tag
rawValue reflect.Value // the raw tag value
err error // the custom error for binding or validating
}
const (
fileTypeString = "*multipart.FileHeader"
fileTypeString2 = "multipart.FileHeader"
filesTypeString = "[]*multipart.FileHeader"
filesTypeString2 = "[]multipart.FileHeader"
cookieTypeString = "*http.Cookie"
cookieTypeString2 = "http.Cookie"
// fasthttpCookieTypeString = "fasthttp.Cookie"
stringTypeString = "string"
bytesTypeString = "[]byte"
bytes2TypeString = "[]uint8"
)
var (
// TagInValues is values for tag 'in'
TagInValues = map[string]bool{
"path": true,
"query": true,
"formData": true,
"body": true,
"header": true,
"cookie": true,
}
)
// Raw gets the param's original value
func (param *Param) Raw() interface{} {
return param.rawValue.Interface()
}
// APIName gets ParamsAPI name
func (param *Param) APIName() string {
return param.apiName
}
// Name gets parameter field name
func (param *Param) Name() string {
return param.name
}
// In get the type value for the param
func (param *Param) In() string {
return param.tags[KEY_IN]
}
// IsRequired tests if the param is declared
func (param *Param) IsRequired() bool {
return param.isRequired
}
// Description gets the description value for the param
func (param *Param) Description() string {
return param.tags[KEY_DESC]
}
// IsFile tests if the param is type *multipart.FileHeader
func (param *Param) IsFile() bool {
return param.isFile
}
func (param *Param) myError(reason string) error {
if param.err != nil {
return param.err
}
return NewError(param.apiName, param.name, reason)
}
// validate tests if the param conforms to it's validation constraints specified
// int the KEY_REGEXP struct tag
func (param *Param) validate(value reflect.Value) (err error) {
defer func() {
p := recover()
if p != nil {
err = param.myError(fmt.Sprint(p))
} else if err != nil {
err = param.myError(err.Error())
}
}()
for _, fn := range param.verifyFuncs {
if err = fn(value); err != nil {
return err
}
}
return nil
}
func (param *Param) makeVerifyFuncs() (err error) {
defer func() {
p := recover()
if p != nil {
err = fmt.Errorf("%v", p)
}
}()
// length
if tuple, ok := param.tags[KEY_LEN]; ok {
if fn, err := validateLen(tuple); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// range
if tuple, ok := param.tags[KEY_RANGE]; ok {
if fn, err := validateRange(tuple); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// nonzero
if _, ok := param.tags[KEY_NONZERO]; ok {
if fn, err := validateNonZero(); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// regexp
if reg, ok := param.tags[KEY_REGEXP]; ok {
var isStrings = param.rawValue.Kind() == reflect.Slice
if fn, err := validateRegexp(isStrings, reg); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
return
}
func parseTuple(tuple string) (string, string) {
c := strings.Split(tuple, ":")
var a, b string
switch len(c) {
case 1:
a = c[0]
if len(a) > 0 {
return a, a
}
case 2:
a = c[0]
b = c[1]
if len(a) > 0 || len(b) > 0 {
return a, b
}
}
panic("invalid validation tuple")
}
func validateNonZero() (func(value reflect.Value) error, error) {
return func(value reflect.Value) error {
obj := value.Interface()
if obj == reflect.Zero(value.Type()).Interface() {
return errors.New("not set")
}
return nil
}, nil
}
func validateLen(tuple string) (func(value reflect.Value) error, error) {
var a, b = parseTuple(tuple)
var min, max int
var err error
if len(a) > 0 {
min, err = strconv.Atoi(a)
if err != nil {
return nil, err
}
}
if len(b) > 0 {
max, err = strconv.Atoi(b)
if err != nil {
return nil, err
}
}
return func(value reflect.Value) error {
length := value.Len()
if len(a) > 0 {
if length < min {
return fmt.Errorf("shorter than %s: %v", a, value.Interface())
}
}
if len(b) > 0 {
if length > max {
return fmt.Errorf("longer than %s: %v", b, value.Interface())
}
}
return nil
}, nil
}
const accuracy = 0.0000001
func validateRange(tuple string) (func(value reflect.Value) error, error) {
var a, b = parseTuple(tuple)
var min, max float64
var err error
if len(a) > 0 {
min, err = strconv.ParseFloat(a, 64)
if err != nil {
return nil, err
}
}
if len(b) > 0 {
max, err = strconv.ParseFloat(b, 64)
if err != nil {
return nil, err
}
}
return func(value reflect.Value) error {
var f64 float64
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f64 = float64(value.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
f64 = float64(value.Uint())
case reflect.Float32, reflect.Float64:
f64 = value.Float()
}
if len(a) > 0 {
if math.Min(f64, min) == f64 && math.Abs(f64-min) > accuracy {
return fmt.Errorf("smaller than %s: %v", a, value.Interface())
}
}
if len(b) > 0 {
if math.Max(f64, max) == f64 && math.Abs(f64-max) > accuracy {
return fmt.Errorf("bigger than %s: %v", b, value.Interface())
}
}
return nil
}, nil
}
func validateRegexp(isStrings bool, reg string) (func(value reflect.Value) error, error) {
re, err := regexp.Compile(reg)
if err != nil {
return nil, err
}
if !isStrings {
return func(value reflect.Value) error {
s := value.String()
if !re.MatchString(s) {
return fmt.Errorf("not match %s: %s", reg, s)
}
return nil
}, nil
} else {
return func(value reflect.Value) error {
for _, s := range value.Interface().([]string) {
if !re.MatchString(s) {
return fmt.Errorf("not match %s: %s", reg, s)
}
}
return nil
}, nil
}
}