-
Notifications
You must be signed in to change notification settings - Fork 8
/
rule.go
439 lines (388 loc) · 12 KB
/
rule.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
package valid
import (
"fmt"
"math"
"net"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/cuigh/auxo/errors"
"github.com/cuigh/auxo/ext/reflects"
)
const (
PatternEmail = `^(?i)([A-Za-z0-9!#$%&'*+\/=?^_{|.}~-]+@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$`
PatternURL = `^(?:(?:https?:\/\/)?(?:[a-z0-9.\-]+|www|[a-z0-9.\-])[.](?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s!()\[\]{};:\'".,<>?]))$`
PatternAlpha string = `^[a-zA-Z]+$`
//PatternAlphaNumeric string = `^[a-zA-Z0-9]+$`
//PatternIPV4 = `^(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`
//PatternIPV6 = `^(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:[0-9A-Fa-f]{1,4}|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::[0-9A-Fa-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?:(?::[0-9A-Fa-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?:(?:(?::[0-9A-Fa-f]{1,4}){1,3})|(?:(?::[0-9A-Fa-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?:(?:(?::[0-9A-Fa-f]{1,4}){1,4})|(?:(?::[0-9A-Fa-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?:(?:(?::[0-9A-Fa-f]{1,4}){1,5})|(?:(?::[0-9A-Fa-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9A-Fa-f]{1,4}:){1}(?:(?:(?::[0-9A-Fa-f]{1,4}){1,6})|(?:(?::[0-9A-Fa-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9A-Fa-f]{1,4}){1,7})|(?:(?::[0-9A-Fa-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$`
//PatternIP = PatternIPV4 + `|` + PatternIPV6
)
var (
regexEmail = regexp.MustCompile(PatternEmail)
regexURL = regexp.MustCompile(PatternURL)
regexAlpha = regexp.MustCompile(PatternAlpha)
)
var (
rules = map[string]Rule{
//"width": nil, // string width, for CJK character, width is 2
//"count": nil, // rune count
"required": requiredRule,
"length": lengthRule,
"range": rangeRule,
"email": matchRule("email", regexEmail),
"url": matchRule("url", regexURL),
"alpha": matchRule("alpha", regexAlpha),
"regex": regexRule,
"ip": ipRule,
"ipv4": ipv4Rule,
"ipv6": ipv6Rule,
}
messages = map[string]string{
"$kind": "rule `${rule}` can't apply to field `${name}`(${type})",
"required": "field `${name}` is required",
"length1": "length must be ${argv}(not ${value})",
"length2": "length must in range ${arg}(not ${value})",
"range1": "value must be ${argv}(not ${value})",
"range2": "value must in range ${arg}(not %v)",
"email": "`${value}` is not a valid email address",
"url": "`${value}` is not a valid URL address",
"alpha": "`${value}` contains non-alpha letters",
"regex": "`${value}` doesn't match regex `${argv}`",
"ip": "`${value}` is not a valid IP address",
"ipv4": "`${value}` is not a valid IPV4 address",
"ipv6": "`${value}` is not a valid IPV6 address",
}
)
type ArgumentFlag byte
const (
LeftOpen = '('
LeftSquare = '['
RightOpen = ')'
RightSquare = ']'
)
type Context struct {
Value reflect.Value
Info *reflect.StructField
messages map[string]string
}
type Argument struct {
Value string
Left, Right ArgumentFlag
}
func (arg *Argument) String() string {
return string(arg.Left) + arg.Value + string(arg.Right)
}
type Rule func(ctx *Context, arg *Argument) error
func requiredRule(ctx *Context, arg *Argument) error {
v := reflects.Indirect(ctx.Value)
ok := v.IsValid()
if ok {
switch v.Kind() {
case reflect.String, reflect.Slice, reflect.Array, reflect.Map, reflect.Chan:
ok = v.Len() > 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
ok = v.Int() != 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
ok = v.Uint() != 0
case reflect.Float32, reflect.Float64:
ok = v.Float() != 0
default:
ok = true
}
}
return assert(ok, "required", ctx, arg, v.Interface())
}
func matchRule(name string, r *regexp.Regexp) Rule {
return func(ctx *Context, arg *Argument) error {
v := reflects.Indirect(ctx.Value)
if err := assertKind(name, ctx, v, reflect.String); err != nil {
return err
}
if s := v.String(); s != "" {
return assert(r.MatchString(s), name, ctx, arg, s)
}
return nil
}
}
func ipRule(ctx *Context, arg *Argument) error {
v := reflects.Indirect(ctx.Value)
if err := assertKind("ip", ctx, v, reflect.String); err != nil {
return err
}
s := v.String()
ip := net.ParseIP(s)
return assert(ip != nil, "ip", ctx, arg, s)
}
func ipv4Rule(ctx *Context, arg *Argument) error {
v := reflects.Indirect(ctx.Value)
if err := assertKind("ipv4", ctx, v, reflect.String); err != nil {
return err
}
s := v.String()
ip := net.ParseIP(s)
return assert(ip != nil && strings.Contains(s, "."), "ipv4", ctx, arg, s)
}
func ipv6Rule(ctx *Context, arg *Argument) error {
v := reflects.Indirect(ctx.Value)
if err := assertKind("ipv6", ctx, v, reflect.String); err != nil {
return err
}
s := v.String()
ip := net.ParseIP(s)
return assert(ip != nil && strings.Contains(s, ":"), "ipv6", ctx, arg, s)
}
func regexRule(ctx *Context, arg *Argument) error {
if arg.Value == "" {
return errors.Format("rule `regex` expected a pattern argument like: (\\d+) etc")
}
v := reflects.Indirect(ctx.Value)
if err := assertKind("regex", ctx, v, reflect.String); err != nil {
return err
}
if s := v.String(); s != "" {
ok, _ := regexp.MatchString(arg.Value, s)
return assert(ok, "regex", ctx, arg, s)
}
return nil
}
// lengthRule can apply to string/slice/map/chan type.
func lengthRule(ctx *Context, arg *Argument) error {
if arg.Value == "" || arg.Value == "~" {
return errors.Format("rule `length` expected 1-2 arguments like: (5), [3~8) etc")
}
pair := strings.Split(arg.Value, "~")
if len(pair) > 2 {
return errors.Format("invalid argument for rule `length`: %v", arg.Value)
}
v := reflects.Indirect(ctx.Value)
if err := assertKind("length", ctx, v, reflect.String, reflect.Slice, reflect.Map, reflect.Chan); err != nil {
return err
}
l := v.Len()
if len(pair) == 1 {
length, err := strconv.Atoi(arg.Value)
if err != nil {
return err
}
return assert(l == length, "length1", ctx, arg, l)
} else if len(pair) == 2 {
start, err := toInt(pair[0], -1)
if err != nil {
return err
}
end, err := toInt(pair[1], math.MaxInt32)
if err != nil {
return err
}
if arg.Left == LeftOpen {
err = assert(l > start, "length2", ctx, arg, l)
} else if arg.Left == LeftSquare {
err = assert(l >= start, "length2", ctx, arg, l)
}
if err != nil {
return err
}
if arg.Right == RightOpen {
err = assert(l < end, "length2", ctx, arg, l)
} else if arg.Right == RightSquare {
err = assert(l <= end, "length2", ctx, arg, l)
}
if err != nil {
return err
}
}
return nil
}
// rangeRule can apply to number types.
func rangeRule(ctx *Context, arg *Argument) error {
if arg.Value == "" || arg.Value == "," {
return errors.Format("rule `range` expected 1-2 arguments like: (5), [3~8) etc")
}
pair := strings.Split(arg.Value, "~")
if len(pair) > 2 {
return errors.Format("invalid argument for rule `range`: %v", arg.Value)
}
v := reflects.Indirect(ctx.Value)
if err := assertKind("range", ctx, v, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64); err != nil {
return err
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value := v.Int()
if len(pair) == 1 {
expected, err := strconv.ParseInt(arg.Value, 10, 64)
if err != nil {
return err
}
return assert(value == expected, "range1", ctx, arg, value)
}
start, err := toInt64(pair[0], -1)
if err != nil {
return err
}
end, err := toInt64(pair[1], int64(math.MaxInt32))
if err != nil {
return err
}
if arg.Left == LeftOpen {
err = assert(value > start, "range2", ctx, arg, value)
} else if arg.Left == LeftSquare {
err = assert(value >= start, "range2", ctx, arg, value)
}
if err != nil {
return err
}
if arg.Right == RightOpen {
err = assert(value < end, "range2", ctx, arg, value)
} else if arg.Right == RightSquare {
err = assert(value <= end, "range2", ctx, arg, value)
}
if err != nil {
return err
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
value := v.Uint()
if len(pair) == 1 {
expected, err := strconv.ParseUint(arg.Value, 10, 64)
if err != nil {
return err
}
return assert(value == expected, "range1", ctx, arg, value)
}
start, err := toUint64(pair[0], 0)
if err != nil {
return err
}
end, err := toUint64(pair[1], uint64(math.MaxUint32))
if err != nil {
return err
}
if arg.Left == LeftOpen {
err = assert(value > start, "range2", ctx, arg, value)
} else if arg.Left == LeftSquare {
err = assert(value >= start, "range2", ctx, arg, value)
}
if err != nil {
return err
}
if arg.Right == RightOpen {
err = assert(value < end, "range2", ctx, arg, value)
} else if arg.Right == RightSquare {
err = assert(value <= end, "range2", ctx, arg, value)
}
if err != nil {
return err
}
case reflect.Float32, reflect.Float64:
value := v.Float()
if len(pair) == 1 {
expected, err := strconv.ParseFloat(arg.Value, 64)
if err != nil {
return err
}
return assert(value == expected, "range1", ctx, arg, value)
}
start, err := toFloat64(pair[0], -1)
if err != nil {
return err
}
end, err := toFloat64(pair[1], float64(math.MaxUint32))
if err != nil {
return err
}
if arg.Left == LeftOpen {
err = assert(value > start, "range2", ctx, arg, value)
} else if arg.Left == LeftSquare {
err = assert(value >= start, "range2", ctx, arg, value)
}
if err != nil {
return err
}
if arg.Right == RightOpen {
err = assert(value < end, "range2", ctx, arg, value)
} else if arg.Right == RightSquare {
err = assert(value <= end, "range2", ctx, arg, value)
}
if err != nil {
return err
}
}
return nil
}
func toInt(s string, def int) (int, error) {
if s == "" {
return def, nil
}
return strconv.Atoi(s)
}
func toInt64(s string, def int64) (int64, error) {
if s == "" {
return def, nil
}
return strconv.ParseInt(s, 10, 64)
}
func toUint64(s string, def uint64) (uint64, error) {
if s == "" {
return def, nil
}
return strconv.ParseUint(s, 10, 64)
}
func toFloat64(s string, def float64) (float64, error) {
if s == "" {
return def, nil
}
return strconv.ParseFloat(s, 64)
}
func assertKind(rule string, ctx *Context, value reflect.Value, kinds ...reflect.Kind) error {
for _, kind := range kinds {
if kind == value.Kind() {
return nil
}
}
msg := ctx.messages["$kind"]
return errors.New(os.Expand(msg, func(name string) string {
switch name {
case "rule":
return rule
case "name":
return ctx.Info.Name
case "type":
return value.Type().String()
default:
return ""
}
}))
}
func assert(ok bool, name string, ctx *Context, arg *Argument, value interface{}) error {
if !ok {
return failed(name, ctx, arg, value)
}
return nil
}
func failed(name string, ctx *Context, arg *Argument, value interface{}) error {
msg := ctx.messages[name]
if msg == "" {
msg = messages[name]
}
if msg == "" {
panic("can not find message for: " + name)
}
return errors.New(os.Expand(msg, func(name string) string {
switch name {
case "name":
return ctx.Info.Name
case "value":
return fmt.Sprint(value)
case "arg":
return arg.String()
case "argv":
return arg.Value
default:
return "[" + name + "]"
}
}))
}