/
param.go
282 lines (258 loc) · 6.93 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
// 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 (
"fmt"
"math"
"reflect"
"regexp"
"strconv"
"strings"
)
const (
TAG_PARAM = "param" //request param tag name
TAG_REGEXP = "regexp" //regexp validate tag name(optio)
TAG_ERR = "err" //the custom error for binding or validating
TAG_IGNORE_PARAM = "-" //ignore request param tag value
MB = 1 << 20 // 1MB
defaultMaxMemory = 32 * MB // 32 MB
defaultMaxMemoryMB = 32
)
// func ParseTags(s string) map[string]string {
// c := strings.Split(s, ",")
// m := make(map[string]string)
// for _, v := range c {
// c2 := strings.Split(v, "(")
// if len(c2) == 2 && len(c2[1]) > 1 {
// m[c2[0]] = c2[1][:len(c2[1])-1]
// } else {
// m[v] = ""
// }
// }
// return m
// }
func ParseTags(s string) map[string]string {
c := strings.Split(s, ",")
m := make(map[string]string)
for _, v := range c {
a := strings.IndexByte(v, '(')
b := strings.LastIndexByte(v, ')')
if a != -1 && b != -1 {
m[v[:a]] = v[a+1 : b]
continue
}
m[v] = ""
}
return m
}
// 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
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"
cookieTypeString = "http.Cookie"
fasthttpCookieTypeString = "fasthttp.Cookie"
stringTypeString = "string"
bytesTypeString = "[]byte"
bytes2TypeString = "[]uint8"
)
var (
// 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["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["desc"]
}
// IsFile tests if the param is type *multipart.FileHeader
func (param *Param) IsFile() bool {
return param.isFile
}
func (param *Param) validate(value reflect.Value) error {
if value.Kind() != reflect.Slice {
return param.validateElem(value)
}
var err error
for i, count := 0, value.Len(); i < count; i++ {
if err = param.validateElem(value.Index(i)); err != nil {
return err
}
}
return nil
}
// Validate tests if the param conforms to it's validation constraints specified
// int the TAG_REGEXP struct tag
func (param *Param) validateElem(value reflect.Value) (err error) {
defer func() {
p := recover()
if param.err != nil {
if err != nil {
err = param.err
}
} else if p != nil {
err = fmt.Errorf("%v", p)
}
}()
// range
if tuple, ok := param.tags["range"]; ok {
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 err = validateRange(f64, tuple, param.name); err != nil {
return err
}
}
obj := value.Interface()
// nonzero
if _, ok := param.tags["nonzero"]; ok {
if value.Kind() != reflect.Struct && obj == reflect.Zero(value.Type()).Interface() {
return NewValidationError(ValidationErrorValueNotSet, param.name)
}
}
s, isString := obj.(string)
// length
if tuple, ok := param.tags["len"]; ok && isString {
if err = validateLen(s, tuple, param.name); err != nil {
return err
}
}
// regexp
if reg, ok := param.tags[TAG_REGEXP]; ok && isString {
if err = validateRegexp(s, reg, param.name); err != nil {
return err
}
}
return
}
func (param *Param) myError(reason string) error {
if param.err != nil {
return param.err
}
return NewError(param.apiName, param.name, reason)
}
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 validateLen(s, tuple, paramName string) error {
a, b := parseTuple(tuple)
if len(a) > 0 {
min, err := strconv.Atoi(a)
if err != nil {
panic(err)
}
if len(s) < min {
return NewValidationError(ValidationErrorValueTooShort, paramName)
}
}
if len(b) > 0 {
max, err := strconv.Atoi(b)
if err != nil {
panic(err)
}
if len(s) > max {
return NewValidationError(ValidationErrorValueTooLong, paramName)
}
}
return nil
}
const accuracy = 0.0000001
func validateRange(f64 float64, tuple, paramName string) error {
a, b := parseTuple(tuple)
if len(a) > 0 {
min, err := strconv.ParseFloat(a, 64)
if err != nil {
return err
}
if math.Min(f64, min) == f64 && math.Abs(f64-min) > accuracy {
return NewValidationError(ValidationErrorValueTooSmall, paramName)
}
}
if len(b) > 0 {
max, err := strconv.ParseFloat(b, 64)
if err != nil {
return err
}
if math.Max(f64, max) == f64 && math.Abs(f64-max) > accuracy {
return NewValidationError(ValidationErrorValueTooBig, paramName)
}
}
return nil
}
func validateRegexp(s, reg, paramName string) error {
matched, err := regexp.MatchString(reg, s)
if err != nil {
return err
}
if !matched {
return NewValidationError(ValidationErrorValueNotMatch, paramName)
}
return nil
}