-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvalidate.go
More file actions
504 lines (433 loc) · 14.2 KB
/
validate.go
File metadata and controls
504 lines (433 loc) · 14.2 KB
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
package validate
import (
"encoding/json"
"fmt"
"github.com/expr-lang/expr"
"github.com/simonalong/gole/constants"
"reflect"
"sort"
"strings"
"sync"
"github.com/simonalong/gole/goid"
"github.com/simonalong/gole/logger"
"github.com/simonalong/gole/util"
"github.com/simonalong/gole/validate/matcher"
)
var lock sync.Mutex
type MatchCollector func(objectTypeFullName string, fieldKind reflect.Kind, objectFieldName string, tagName string, subCondition string, errCode, errMsg string)
type CollectorEntity struct {
name string
infCollector MatchCollector
}
type CheckResult struct {
Result bool
ErrCode string
ErrMsg string
}
var checkerEntities []CollectorEntity
/* 核查的标签 */
var matchTagArray = []string{constants.Value, constants.IsBlank, constants.Range, constants.Model, constants.Condition, constants.Regex, constants.Customize}
// Check
// 入参
// - object: 检查对象
// - fieldNames...: 待检查对象的属性
//
// 返回值
// - bool: 核查结果
// - string: 错误code
// - string: 错误异常
func Check(object any, fieldNames ...string) (bool, string, string) {
return CheckWithParameter(map[string]interface{}{}, object, fieldNames...)
}
// CheckWithParameter
// 入参
// - parameterMap: 外部参数map,这个一般用于'customize'自定义函数里面的参数用
// - object: 检查对象
// - fieldNames...: 待检查对象的属性
//
// 返回值
// - bool: 核查结果
// - string: 错误code
// - string: 错误异常
func CheckWithParameter(parameterMap map[string]interface{}, object interface{}, fieldNames ...string) (bool, string, string) {
if object == nil {
return true, "", ""
}
objType := reflect.TypeOf(object)
objValue := reflect.ValueOf(object)
// 指针类型按照指针类型
if objType.Kind() == reflect.Ptr {
objValue = objValue.Elem()
objType = objType.Elem()
}
if objType.Kind() != reflect.Struct {
return true, "", ""
}
// 搜集核查器
collectCollector(objType)
ch := make(chan *CheckResult)
for index, num := 0, objType.NumField(); index < num; index++ {
field := objType.Field(index)
fieldValue := objValue.Field(index)
// 私有字段不处理
if !util.IsPublic(field.Name) {
continue
}
// 过滤选择的列
if !isSelectField(field.Name, fieldNames...) {
continue
}
// 基本类型
if matcher.IsCheckedKing(fieldValue.Type()) || (fieldValue.Kind() == reflect.Ptr && !fieldValue.Elem().IsValid()) || (fieldValue.Kind() == reflect.Ptr && matcher.IsCheckedKing(fieldValue.Elem().Type())) {
tagJudge := field.Tag.Get(constants.MATCH)
if len(tagJudge) == 0 {
continue
}
// 核查结果:任何一个属性失败,则返回失败
goid.Go(func() {
check(parameterMap, object, field, fieldValue.Interface(), ch)
})
checkResult := <-ch
if !checkResult.Result {
close(ch)
return false, checkResult.ErrCode, checkResult.ErrMsg
}
} else if fieldValue.Kind() == reflect.Struct || (fieldValue.Kind() == reflect.Ptr && fieldValue.Elem().Kind() == reflect.Struct) {
// struct 结构类型
tagMatch := field.Tag.Get(constants.MATCH)
if len(tagMatch) == 0 || (len(tagMatch) == 1 && tagMatch != constants.CHECK) {
continue
}
result, errCode, errMsg := Check(fieldValue.Interface())
if !result {
return false, errCode, errMsg
}
} else if fieldValue.Kind() == reflect.Map || (fieldValue.Kind() == reflect.Ptr && fieldValue.Elem().Kind() == reflect.Map) {
// map结构
if fieldValue.Len() == 0 {
continue
}
for mapR := fieldValue.MapRange(); mapR.Next(); {
mapKey := mapR.Key()
mapValue := mapR.Value()
result, errCode, errMsg := Check(mapKey.Interface())
if !result {
return false, errCode, errMsg
}
result, errCode, errMsg = Check(mapValue.Interface())
if !result {
return false, errCode, errMsg
}
}
} else if fieldValue.Kind() == reflect.Array || (fieldValue.Kind() == reflect.Ptr && fieldValue.Elem().Kind() == reflect.Array) {
// Array 结构
arrayLen := fieldValue.Len()
for arrayIndex := 0; arrayIndex < arrayLen; arrayIndex++ {
fieldValueItem := fieldValue.Index(arrayIndex)
result, errCode, errMsg := Check(fieldValueItem.Interface())
if !result {
return false, errCode, errMsg
}
}
} else if fieldValue.Kind() == reflect.Slice || (fieldValue.Kind() == reflect.Ptr && fieldValue.Elem().Kind() == reflect.Slice) {
// Slice 结构
tagJudge := field.Tag.Get(constants.MATCH)
if len(tagJudge) == 0 {
continue
}
// 核查结果:任何一个属性失败,则返回失败
goid.Go(func() {
check(parameterMap, object, field, fieldValue.Interface(), ch)
})
checkResult := <-ch
if !checkResult.Result {
close(ch)
return false, checkResult.ErrCode, checkResult.ErrMsg
}
arrayLen := fieldValue.Len()
for arrayIndex := 0; arrayIndex < arrayLen; arrayIndex++ {
fieldValueItem := fieldValue.Index(arrayIndex)
result, errCode, errMsg := Check(fieldValueItem.Interface())
if !result {
return false, errCode, errMsg
}
}
}
}
close(ch)
return true, "", ""
}
// 搜集核查器
func collectCollector(objType reflect.Type) {
objectFullName := objType.String()
/* 搜集过则不再搜集 */
if _, contain := matcher.MatchMap[objectFullName]; contain {
return
}
lock.Lock()
defer lock.Unlock()
/* 搜集过则不再搜集 */
if _, contain := matcher.MatchMap[objectFullName]; contain {
return
}
doCollectCollector(objType)
}
func doCollectCollector(objType reflect.Type) {
// 基本类型不需要搜集
if matcher.IsCheckedKing(objType) {
return
}
// 指针类型按照指针类型
if objType.Kind() == reflect.Ptr {
doCollectCollector(objType.Elem())
return
}
if objType.Kind() != reflect.Struct {
return
}
objectFullName := objType.String()
for fieldIndex, num := 0, objType.NumField(); fieldIndex < num; fieldIndex++ {
field := objType.Field(fieldIndex)
fieldKind := field.Type.Kind()
// 不可访问字段不处理
if !util.IsPublic(field.Name) {
continue
}
if fieldKind == reflect.Ptr {
fieldKind = field.Type.Elem().Kind()
}
// 禁用
tagMatch := field.Tag.Get(constants.Disable)
if len(tagMatch) != 0 && tagMatch == "true" {
continue
}
// 基本类型
if matcher.IsCheckedKing(field.Type) {
// 错误码信息
errMsg := field.Tag.Get(constants.ErrMsg)
// 错误码code
errCode := field.Tag.Get(constants.ErrCode)
// match
tagMatch := field.Tag.Get(constants.MATCH)
if len(tagMatch) == 0 {
continue
}
if _, contain := matcher.MatchMap[objectFullName][field.Name]; !contain {
addMatcher(objectFullName, fieldKind, field.Name, tagMatch, errCode, errMsg)
}
// accept
tagAccept := field.Tag.Get(constants.Accept)
if len(tagMatch) == 0 {
continue
}
if _, contain := matcher.MatchMap[objectFullName][field.Name]; contain {
addCollector(objectFullName, fieldKind, field.Name, constants.Accept, tagAccept, errCode, errMsg)
}
} else if fieldKind == reflect.Struct {
// struct 结构类型
tagMatch := field.Tag.Get(constants.MATCH)
if len(tagMatch) == 0 || (len(tagMatch) == 1 && tagMatch != constants.CHECK) {
continue
}
doCollectCollector(field.Type)
} else if fieldKind == reflect.Map {
// Map 结构
doCollectCollector(field.Type.Key())
doCollectCollector(field.Type.Elem())
} else if fieldKind == reflect.Array {
// Array 结构
doCollectCollector(field.Type.Elem())
} else if fieldKind == reflect.Slice {
// Slice 结构
// 错误码信息
errMsg := field.Tag.Get(constants.ErrMsg)
// 错误码code
errCode := field.Tag.Get(constants.ErrCode)
// match
tagMatch := field.Tag.Get(constants.MATCH)
if len(tagMatch) == 0 {
continue
}
if _, contain := matcher.MatchMap[objectFullName][field.Name]; !contain {
addMatcher(objectFullName, fieldKind, field.Name, tagMatch, errCode, errMsg)
}
// accept
tagAccept := field.Tag.Get(constants.Accept)
if len(tagMatch) == 0 {
continue
}
if _, contain := matcher.MatchMap[objectFullName][field.Name]; !contain {
addCollector(objectFullName, fieldKind, field.Name, constants.Accept, tagAccept, errCode, errMsg)
}
doCollectCollector(field.Type.Elem())
} else {
// Uintptr 类型不处理
}
}
}
// 是否是选择的列,没有选择也认为是选择的
func isSelectField(fieldName string, fieldNames ...string) bool {
if len(fieldNames) == 0 {
return true
}
for _, name := range fieldNames {
// 不区分大小写
if strings.EqualFold(name, fieldName) {
return true
}
}
return false
}
// 搜集处理器,对于有一些空格的也进行单独处理
func addMatcher(objectFullName string, fieldKind reflect.Kind, fieldName string, matchJudge string, errCode, errMsg string) {
var subStrIndexes []int
for _, tag := range matchTagArray {
index := strings.Index(matchJudge, tag)
if index != -1 {
subStrIndexes = append(subStrIndexes, index)
}
}
sort.Ints(subStrIndexes)
lastIndex := 0
for _, subIndex := range subStrIndexes {
if lastIndex == subIndex {
continue
}
subJudgeStr := matchJudge[lastIndex:subIndex]
buildChecker(objectFullName, fieldKind, fieldName, constants.MATCH, subJudgeStr, errCode, errMsg)
lastIndex = subIndex
}
subJudgeStr := matchJudge[lastIndex:]
buildChecker(objectFullName, fieldKind, fieldName, constants.MATCH, subJudgeStr, errCode, errMsg)
}
// 添加搜集器
func addCollector(objectFullName string, fieldKind reflect.Kind, fieldName string, tagName string, matchJudge string, errCode, errMsg string) {
buildChecker(objectFullName, fieldKind, fieldName, tagName, matchJudge, errCode, errMsg)
}
func buildChecker(objectFullName string, fieldKind reflect.Kind, fieldName string, tagName string, subStr string, errCode, errMsg string) {
for _, entity := range checkerEntities {
entity.infCollector(objectFullName, fieldKind, fieldName, tagName, subStr, errCode, errMsg)
}
}
func check(parameterMap map[string]interface{}, object any, field reflect.StructField, fieldRelValue any, ch chan *CheckResult) {
objectType := reflect.TypeOf(object)
if objectType.Kind() == reflect.Ptr {
objectType = objectType.Elem()
}
if fieldMatcher, contain := matcher.MatchMap[objectType.String()][field.Name]; contain {
accept := fieldMatcher.Accept
errMsgOfMatcherProgram := fieldMatcher.ErrMsgProgram
errCodeOfMatcher := fieldMatcher.ErrCode
matchers := fieldMatcher.Matchers
// 黑名单,而且匹配到,则核查失败
if !accept {
if matchResult, _errCode, _errMsg := judgeMatch(matchers, parameterMap, object, field, fieldRelValue, accept); matchResult {
errMsgFinal := ""
errCodeFinal := errCodeOfMatcher
if errMsgOfMatcherProgram != nil {
env := map[string]any{
"sprintf": fmt.Sprintf,
"root": object,
"current": fieldRelValue,
}
output, err := expr.Run(errMsgOfMatcherProgram, env)
if err != nil {
logger.Error(err.Error())
ch <- &CheckResult{Result: false, ErrMsg: err.Error()}
return
}
result := fmt.Sprintf("%v", output)
errMsgFinal = result
} else {
errMsgFinal = _errMsg
}
if _errCode != "" {
errCodeFinal = _errCode
}
ch <- &CheckResult{Result: false, ErrCode: errCodeFinal, ErrMsg: errMsgFinal}
return
}
}
// 白名单,没有匹配到,则核查失败
if accept {
if matchResult, _errCode, _errMsg := judgeMatch(matchers, parameterMap, object, field, fieldRelValue, accept); !matchResult {
errMsgFinal := ""
errCodeFinal := errCodeOfMatcher
if errMsgOfMatcherProgram != nil {
env := map[string]any{
"sprintf": fmt.Sprintf,
"root": object,
"current": fieldRelValue,
}
output, err := expr.Run(errMsgOfMatcherProgram, env)
if err != nil {
logger.Error(err.Error())
ch <- &CheckResult{Result: false, ErrMsg: err.Error()}
return
}
result := fmt.Sprintf("%v", output)
errMsgFinal = result
} else {
errMsgFinal = _errMsg
}
if _errCode != "" {
errCodeFinal = _errCode
}
ch <- &CheckResult{Result: false, ErrCode: errCodeFinal, ErrMsg: errMsgFinal}
return
}
}
}
ch <- &CheckResult{Result: true}
return
}
// 任何一个匹配上,则返回true,都没有匹配上则返回false
func judgeMatch(matchers []*matcher.Matcher, parameterMap map[string]interface{}, object any, field reflect.StructField, fieldValue any, accept bool) (bool, string, string) {
var errMsgArray []string
var errCode string
for _, match := range matchers {
if (*match).IsEmpty() {
continue
}
matchResult := (*match).Match(parameterMap, object, field, fieldValue)
if matchResult {
if !accept {
errMsgArray = append(errMsgArray, (*match).GetBlackMsg())
errCode = (*match).GetErrCode()
} else {
errMsgArray = []string{}
}
return true, errCode, arraysToString(errMsgArray)
} else {
if accept {
errMsgArray = append(errMsgArray, (*match).GetWhitMsg())
errCode = (*match).GetErrCode()
}
}
}
return false, errCode, arraysToString(errMsgArray)
}
func RegisterCustomize(funName string, fun any) {
matcher.RegisterCustomize(funName, fun)
}
// 包的初始回调
func init() {
/* 匹配后是否接受 */
checkerEntities = append(checkerEntities, CollectorEntity{constants.Accept, matcher.CollectAccept})
/* 搜集匹配器 */
checkerEntities = append(checkerEntities, CollectorEntity{constants.Value, matcher.BuildValuesMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.IsBlank, matcher.BuildIsBlankMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.IsUnBlank, matcher.BuildIsUnBlankMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.Range, matcher.BuildRangeMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.Model, matcher.BuildModelMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.Condition, matcher.BuildConditionMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.Customize, matcher.BuildCustomizeMatcher})
checkerEntities = append(checkerEntities, CollectorEntity{constants.Regex, matcher.BuildRegexMatcher})
}
func arraysToString(dataArray []string) string {
if len(dataArray) == 1 {
return dataArray[0]
}
myValue, _ := json.Marshal(dataArray)
return string(myValue)
}