-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
640 lines (591 loc) · 16.7 KB
/
validator.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
package validator
import (
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
)
type RuleSet interface {
Description(string) RuleSet
Require(bool) RuleSet
MustLength(int) RuleSet
MustInt() RuleSet
MustInt64() RuleSet
MustBool() RuleSet
MustMin(int) RuleSet
MustMax(int) RuleSet
MustSeparator(string, reflect.Kind) RuleSet
MustLengthRange(int, int) RuleSet
MustValues([]interface{}) RuleSet
MustTimeLayout(string) RuleSet
MustLessThan(string) RuleSet
MustLargeThan(string) RuleSet
MustFunc(ValidationFunc, []interface{}) RuleSet
}
const (
ValidTag = "valid"
ValidateTag = "validate"
)
type ValidationFunc func(string, interface{}, url.Values, bool, ...interface{}) error
type Params struct {
Type string
Description string
Require bool
Rules []rule
}
type Validator struct {
IgnoreUnknownParams bool
CustomError bool
ApiParams map[string]*Params
requireParams []string
requireUrlParams []string
splitChar string
ruleMap map[string][]rule
valueMap map[string]interface{}
defaultValueMap map[string]interface{}
typeMap map[string]reflect.Kind
elemTypeMap map[string]reflect.Kind
typeErrMap map[string]error
}
func NewValidator() *Validator {
v := new(Validator)
v.IgnoreUnknownParams = true
v.ApiParams = make(map[string]*Params)
v.ruleMap = make(map[string][]rule)
v.typeMap = make(map[string]reflect.Kind)
v.elemTypeMap = make(map[string]reflect.Kind)
v.valueMap = make(map[string]interface{})
v.defaultValueMap = make(map[string]interface{})
return v
}
func Validate(params url.Values, v *Validator) error {
for _, p := range v.requireParams {
if values, ok := params[p]; !ok {
Perr := new(ParamsError)
Perr.Key = p
Perr.ErrRequireParam(v.CustomError)
return Perr
} else if values[0] == "" {
Perr := new(ParamsError)
Perr.Key = p
Perr.ErrRequireNotNull(v.CustomError)
return Perr
}
}
for key, value := range params {
if value[0] == "" {
continue
}
if rules, ok := v.ruleMap[key]; ok {
err := v.valueCheck(key, value[0])
if err != nil {
return err
}
for _, rule := range rules {
if rule.f != nil {
var err error
if valueInterface, ok := v.valueMap[key]; ok {
err = rule.f(key, valueInterface, params, v.CustomError, rule.args...)
} else {
err = rule.f(key, value[0], params, v.CustomError, rule.args...)
}
if err != nil {
return err
}
}
}
} else {
Perr := NewParamsError(key, value[0])
Perr.ErrUnknownParam(v.CustomError)
return Perr
}
}
return nil
}
func UrlValidator(params map[string]string, v *Validator) error {
for _, p := range v.requireUrlParams {
if value, ok := params[p]; !ok {
Perr := new(ParamsError)
Perr.Key = p
Perr.ErrRequireParam(v.CustomError)
return Perr
} else if value == "" {
Perr := new(ParamsError)
Perr.Key = p
Perr.ErrRequireNotNull(v.CustomError)
return Perr
}
}
for key, value := range params {
if value == "" {
continue
}
if rules, ok := v.ruleMap[key]; ok {
err := v.valueCheck(key, value)
if err != nil {
return err
}
for _, rule := range rules {
if rule.f != nil {
var err error
if valueInterface, ok := v.valueMap[key]; ok {
err = rule.f(key, valueInterface, nil, v.CustomError, rule.args...)
} else {
err = rule.f(key, value, nil, v.CustomError, rule.args...)
}
if err != nil {
return err
}
}
}
} else {
Perr := NewParamsError(key, value)
Perr.ErrUnknownParam(v.CustomError)
return Perr
}
}
return nil
}
type ruleSet struct {
valid *Validator
is_url_param bool
paramName string
setError error
}
type rule struct {
f ValidationFunc
args []interface{}
errMsg error
}
var _ RuleSet = new(ruleSet)
func (v *Validator) Clone() *Validator {
valid := Validator{
IgnoreUnknownParams: v.IgnoreUnknownParams,
CustomError: v.CustomError,
ApiParams: v.ApiParams,
requireParams: v.requireParams,
requireUrlParams: v.requireUrlParams,
splitChar: v.splitChar,
ruleMap: v.ruleMap,
valueMap: make(map[string]interface{}),
defaultValueMap: v.defaultValueMap,
typeMap: v.typeMap,
elemTypeMap: v.elemTypeMap,
typeErrMap: v.typeErrMap,
}
return &valid
}
func (v *Validator) NewParam(paramName string, value ...interface{}) RuleSet {
p := new(Params)
p.Type = reflect.String.String()
v.ApiParams[paramName] = p
r := new(ruleSet)
r.paramName = paramName
r.valid = v
r.valid.typeMap[paramName] = reflect.String
if len(value) == 1 {
r.valid.defaultValueMap[paramName] = value[0]
}
r.valid.ruleMap[paramName] = append(r.valid.ruleMap[paramName], *new(rule))
return r
}
func (v *Validator) NewUrlParam(paramName string, value ...interface{}) RuleSet {
p := new(Params)
p.Type = reflect.String.String()
v.ApiParams[paramName] = p
r := new(ruleSet)
r.paramName = paramName
r.is_url_param = true
r.valid = v
r.valid.typeMap[paramName] = reflect.String
if len(value) == 1 {
r.valid.defaultValueMap[paramName] = value[0]
}
r.valid.ruleMap[paramName] = append(r.valid.ruleMap[paramName], *new(rule))
return r
}
func (v *Validator) SetCustomError() *Validator {
v.CustomError = true
return v
}
func (v *Validator) ValuesToStruct(dst interface{}) error {
vl := reflect.ValueOf(dst)
if vl.Kind() != reflect.Ptr || vl.Elem().Kind() != reflect.Struct {
return NewTextError("interface must be a pointer to struct")
}
vl = vl.Elem()
t := vl.Type()
for i := 0; i < t.NumField(); i++ {
if vl.Field(i).Kind() == reflect.Struct {
st := vl.Field(i).Type()
sv := vl.Field(i)
for j := 0; j < st.NumField(); j++ {
paramName := st.Field(j).Tag.Get(ValidTag)
if _, ok := v.valueMap[paramName]; ok {
switch v.typeMap[paramName] {
case reflect.Int:
sv.Field(j).SetInt(int64(v.valueMap[paramName].(int)))
case reflect.Int64:
sv.Field(j).SetInt(v.valueMap[paramName].(int64))
case reflect.Bool:
sv.Field(j).SetBool(v.valueMap[paramName].(bool))
case reflect.String:
sv.Field(j).SetString(v.valueMap[paramName].(string))
case reflect.Slice:
slicev := reflect.MakeSlice(sv.Field(j).Type(), 0, 0)
vInterface := v.valueMap[paramName].([]interface{})
for _, sliceV := range vInterface {
slicev = reflect.Append(slicev, reflect.ValueOf(sliceV))
}
sv.Field(i).Set(slicev)
}
} else if _, ok := v.defaultValueMap[paramName]; ok {
switch v.typeMap[paramName] {
case reflect.Int:
sv.Field(j).SetInt(int64(v.defaultValueMap[paramName].(int)))
case reflect.Int64:
sv.Field(j).SetInt(v.defaultValueMap[paramName].(int64))
case reflect.Bool:
sv.Field(j).SetBool(v.defaultValueMap[paramName].(bool))
case reflect.String:
sv.Field(j).SetString(v.defaultValueMap[paramName].(string))
case reflect.Slice:
slicev := reflect.MakeSlice(sv.Field(j).Type(), 0, 0)
vInterface := v.defaultValueMap[paramName].([]interface{})
for _, sliceV := range vInterface {
slicev = reflect.Append(slicev, reflect.ValueOf(sliceV))
}
sv.Field(i).Set(slicev)
}
}
}
} else {
paramName := t.Field(i).Tag.Get(ValidTag)
fieldv := vl.Field(i)
if fieldv.Kind() == reflect.Ptr && !fieldv.IsNil() {
fieldv = fieldv.Elem()
}
if _, ok := v.valueMap[paramName]; ok {
if fieldv.Kind() == reflect.Ptr && fieldv.CanSet() {
//对空指针进行初始化,暂时用临时变量保存
fieldv.Set(reflect.New(fieldv.Type().Elem()))
fieldv = fieldv.Elem()
}
switch v.typeMap[paramName] {
case reflect.Int:
fieldv.SetInt(int64(v.valueMap[paramName].(int)))
case reflect.Int64:
fieldv.SetInt(v.valueMap[paramName].(int64))
case reflect.Bool:
fieldv.SetBool(v.valueMap[paramName].(bool))
case reflect.String:
fieldv.SetString(v.valueMap[paramName].(string))
case reflect.Slice:
sv := reflect.MakeSlice(fieldv.Type(), 0, 0)
vInterface := v.valueMap[paramName].([]interface{})
for _, sliceV := range vInterface {
sv = reflect.Append(sv, reflect.ValueOf(sliceV))
}
fieldv.Set(sv)
}
} else if _, ok := v.defaultValueMap[paramName]; ok {
if fieldv.Kind() == reflect.Ptr && fieldv.CanSet() {
//对空指针进行初始化,暂时用临时变量保存
fieldv.Set(reflect.New(fieldv.Type().Elem()))
fieldv = fieldv.Elem()
}
switch v.typeMap[paramName] {
case reflect.Int:
fieldv.SetInt(int64(v.defaultValueMap[paramName].(int)))
case reflect.Int64:
fieldv.SetInt(v.defaultValueMap[paramName].(int64))
case reflect.Bool:
fieldv.SetBool(v.defaultValueMap[paramName].(bool))
case reflect.String:
fieldv.SetString(v.defaultValueMap[paramName].(string))
case reflect.Slice:
sv := reflect.MakeSlice(fieldv.Type(), 0, 0)
vInterface := v.defaultValueMap[paramName].([]interface{})
for _, sliceV := range vInterface {
sv = reflect.Append(sv, reflect.ValueOf(sliceV))
}
fieldv.Set(sv)
}
}
}
}
return nil
}
func (v *Validator) valueCheck(key, value string) error {
if pType, ok := v.typeMap[key]; ok {
var err error
switch pType {
case reflect.Int:
v.valueMap[key], err = strconv.Atoi(value)
if err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是int类型", key)
}
case reflect.Int64:
v.valueMap[key], err = strconv.ParseInt(value, 10, 64)
if err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是int64类型", key)
}
case reflect.Bool:
if valueBool, err := strconv.ParseBool(value); err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是bool类型", key)
} else {
v.valueMap[key] = valueBool
}
case reflect.String:
v.valueMap[key] = value
case reflect.Slice:
var sliceInterface []interface{}
sliceString := strings.Split(value, v.splitChar)
switch v.elemTypeMap[key] {
case reflect.Int:
for _, vString := range sliceString {
vInt, err := strconv.Atoi(vString)
if err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是int类型", key)
}
sliceInterface = append(sliceInterface, vInt)
}
case reflect.Int64:
for _, vString := range sliceString {
vInt64, err := strconv.ParseInt(vString, 10, 64)
if err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是int64类型", key)
}
sliceInterface = append(sliceInterface, vInt64)
}
case reflect.Bool:
for _, vString := range sliceString {
if vBool, err := strconv.ParseBool(vString); err != nil {
if Terr, ok := v.typeErrMap[key]; ok {
return Terr
}
return fmt.Errorf("参数[%s]格式错误,参数值必须是bool类型", key)
} else {
sliceInterface = append(sliceInterface, vBool)
}
}
case reflect.String:
for _, vString := range sliceString {
sliceInterface = append(sliceInterface, vString)
}
}
v.valueMap[key] = sliceInterface
default:
}
}
return nil
}
func (r *ruleSet) Description(description string) RuleSet {
r.valid.ApiParams[r.paramName].Description = description
return r
}
func (r *ruleSet) Require(require bool) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set Require")
}
r.valid.ApiParams[r.paramName].Require = require
if require {
if r.is_url_param {
r.valid.requireUrlParams = append(r.valid.requireUrlParams, r.paramName)
} else {
r.valid.requireParams = append(r.valid.requireParams, r.paramName)
}
}
return r
}
func (r *ruleSet) MustInt() RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustInt")
}
r.valid.ApiParams[r.paramName].Type = reflect.Int.String()
r.valid.typeMap[r.paramName] = reflect.Int
return r
}
func (r *ruleSet) MustInt64() RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustInt")
}
r.valid.ApiParams[r.paramName].Type = reflect.Int64.String()
r.valid.typeMap[r.paramName] = reflect.Int64
return r
}
func (r *ruleSet) MustBool() RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustBool")
}
r.valid.ApiParams[r.paramName].Type = reflect.Bool.String()
r.valid.typeMap[r.paramName] = reflect.Bool
return r
}
func (r *ruleSet) MustSeparator(s string, elemType reflect.Kind) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustBool")
}
r.valid.splitChar = s
r.valid.typeMap[r.paramName] = reflect.Slice
r.valid.elemTypeMap[r.paramName] = elemType
return r
}
func (r *ruleSet) MustLength(length int) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLength")
}
rl := new(rule)
rl.f = mustLength
rl.args = append(rl.args, length)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustMin(min int) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustMin")
}
rl := new(rule)
rl.f = mustMin
rl.args = append(rl.args, min)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustMax(max int) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustMax")
}
rl := new(rule)
rl.f = mustMax
rl.args = append(rl.args, max)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustLengthRange(min, max int) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLengthRange")
}
rl := new(rule)
rl.f = mustLengthRange
rl.args = append(rl.args, min)
rl.args = append(rl.args, max)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustValues(values []interface{}) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLengthRange")
}
rl := new(rule)
rl.f = mustValues
rl.args = append(rl.args, values)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustTimeLayout(layout string) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLengthRange")
}
rl := new(rule)
rl.f = mustTimeLayout
rl.args = append(rl.args, layout)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustLessThan(field string) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLessThan")
}
rl := new(rule)
rl.f = mustLessThan
rl.args = append(rl.args, field)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustLargeThan(field string) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLessThan")
}
rl := new(rule)
rl.f = mustLargeThan
rl.args = append(rl.args, field)
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}
func (r *ruleSet) MustFunc(f ValidationFunc, args []interface{}) RuleSet {
if r.setError != nil {
return r
}
if r.paramName == "" {
panic("unknown param name when set MustLengthRange")
}
rl := new(rule)
rl.f = f
rl.args = args
r.valid.ApiParams[r.paramName].Rules = append(r.valid.ApiParams[r.paramName].Rules, *rl)
r.valid.ruleMap[r.paramName] = append(r.valid.ruleMap[r.paramName], *rl)
return r
}