-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule.go
439 lines (384 loc) · 8.99 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 validate
import (
"fmt"
"reflect"
"regexp"
"strconv"
"time"
)
// Types
const (
Unknown = iota
Int
Float
Number
Bool
String
Time
)
// Type of callbacks to be used in a Rule
type AlterCallback func(value interface{}) interface{}
type PrepareCallback func(value interface{}) interface{}
type CustomCallback func(value interface{}) bool
// Rule encompasses a single validation rule for a parameter
type Rule struct {
// validations
Key string
Type int
Required bool
Regex string
Message string
Min float64
Max float64
Before *time.Time
After *time.Time
In []string
// callbacks
Customs []CustomCallback
Prepares []PrepareCallback
Alters []AlterCallback
// using these since max / min get initialized to 0
DidSetMin bool
DidSetMax bool
}
// Validates an input
func (rule *Rule) Process(input interface{}) (interface{}, []error) {
// ret values
var ok bool
var errors []error
var retInput = input
// type check
coercedInput, ok := rule.TypeOkFor(input)
if !ok { // failed type check
msg := fmt.Sprintf("Bad input type. Expecting type %v. Got: %v", rule.Type, reflect.TypeOf(retInput))
errors = append(errors, fmt.Errorf(msg))
Log.Warning(msg)
} else {
Log.Info("Input '%v' type is: %v", reflect.ValueOf(retInput), reflect.TypeOf(retInput))
retInput = coercedInput
// route return values by type
switch rule.Type {
case Int:
fallthrough
case Float:
fallthrough
case Number:
ok, errors = rule.evalNumber(retInput)
break
case String:
ok, errors = rule.evalString(retInput.(string))
break
case Bool:
ok, errors = rule.evalBoolean(retInput.(bool))
break
case Time:
ok, errors = rule.evalTime(retInput.(time.Time))
break
}
}
Log.Debug("process(...) -> %v, %v", ok, errors)
return retInput, errors
}
/* * * * * * * * * * * * *
Type Eval Functions
* * * * * * * * * * * * */
func (rule *Rule) evalTime(val time.Time) (bool, []error) {
allOk := true
var errors []error
if rule.After != nil {
ok, err := rule.evalAfter(val)
if !ok {
Log.Debug("Given time (%v) failed after test", val)
errors = append(errors, err)
allOk = false
} else {
Log.Debug("Given time (%v) > (%v) -- SUCCESS", val, *rule.After)
}
}
if rule.Before != nil {
ok, err := rule.evalBefore(val)
if !ok {
Log.Debug("Given time (%v) failed after test", val)
errors = append(errors, err)
allOk = false
} else {
Log.Debug("Given time (%v) < (%v) -- SUCCESS", val, *rule.Before)
}
}
return allOk, errors
}
func (rule *Rule) evalBoolean(val bool) (bool, []error) {
return true, []error{}
}
func (rule *Rule) evalString(val string) (bool, []error) {
allOk := true
var errors []error
Log.Debug("Length of regex %v (%v)", len(rule.Regex), rule.Regex)
if len(rule.Regex) > 0 {
ok, err := rule.evalRegex(val)
if !ok {
Log.Debug("Regex failed")
errors = append(errors, err)
allOk = false
} else {
Log.Debug("Regex succeeded")
}
}
if len(rule.In) > 0 {
ok, err := rule.evalIn(val)
if !ok {
Log.Debug("In failed")
errors = append(errors, err)
allOk = false
} else {
Log.Debug("In succeeded")
}
}
return allOk, errors
}
func (rule *Rule) evalNumber(val interface{}) (bool, []error) {
var ok bool
var errors []error
switch val.(type) {
case int32:
ok, errors = rule.evalInt(int(val.(int32)))
case int64:
ok, errors = rule.evalInt(int(val.(int64)))
case int:
ok, errors = rule.evalInt(val.(int))
case float32:
ok, errors = rule.evalFloat(val.(float64))
case float64:
ok, errors = rule.evalFloat(val.(float64))
}
return ok, errors
}
func (rule *Rule) evalInt(val int) (bool, []error) {
return rule.evalFloat(float64(val))
}
func (rule *Rule) evalFloat(val float64) (bool, []error) {
allOk := true
var errors []error
if rule.DidSetMin {
ok, err := rule.evalMin(val)
if !ok {
errors = append(errors, err)
allOk = false
}
}
if rule.DidSetMax {
if ok, err := rule.evalMax(val); !ok {
errors = append(errors, err)
allOk = false
}
}
Log.Debug("evalFloat(...) -> %v, %v", allOk, errors)
return allOk, errors
}
/* * * * * * * * * * * * *
Rule Eval Functions
* * * * * * * * * * * * */
func (rule *Rule) evalBefore(val time.Time) (bool, error) {
ok := true
var err error
if val.After(*rule.Before) {
ok = false
err = fmt.Errorf("[%v] is AFTER %v (expecting it to be BEFORE)", val, rule.Before)
}
return ok, err
}
func (rule *Rule) evalAfter(val time.Time) (bool, error) {
ok := true
var err error
if val.Before(*rule.After) {
ok = false
err = fmt.Errorf("[%v] is BEFORE %v (expecting it to be AFTER)", val, rule.After)
}
return ok, err
}
func (rule *Rule) evalIn(val string) (bool, error) {
ok := false
err := fmt.Errorf("[%v] not in %v", val, rule.In)
Log.Debug("Looking up [%v] in %v", val, rule.In)
for _, inVal := range rule.In {
if inVal == val {
ok = true
err = nil
break
}
}
return ok, err
}
func (rule *Rule) evalRegex(val string) (bool, error) {
ok := true
var err error
Log.Debug("Validating %v =~ %v", val, rule.Regex)
expr, err := regexp.Compile(rule.Regex)
if err == nil {
// check regex
if k := expr.MatchString(val); !k {
Log.Debug("Failed regex")
err = fmt.Errorf("[%v] did not match regex [%v]", val, rule.Regex)
ok = false
} else {
Log.Debug("Passed regex")
}
}
return ok, err
}
func (rule *Rule) evalMin(val float64) (bool, error) {
ok := true
var err error
Log.Debug("Validating %v > %v...", val, rule.Min)
if val < rule.Min {
err = fmt.Errorf("Input(%v) < Minimum(%v)", val, rule.Min)
ok = false
}
return ok, err
}
func (rule *Rule) evalMax(val float64) (bool, error) {
ok := true
var err error
if val > rule.Max {
err = fmt.Errorf("Input(%v) > Maximum(%v)", val, rule.Min)
ok = false
}
return ok, err
}
func (rule *Rule) TypeOkFor(input interface{}) (interface{}, bool) {
var ok bool
var retInput interface{}
switch rule.Type {
case Int:
retInput, ok = input.(int)
if !ok {
retInput, ok = input.(int32)
}
if !ok {
retInput, ok = input.(int64)
}
break
case Float:
retInput, ok = input.(float64)
if !ok {
retInput, ok = input.(float32)
}
break
case Number:
retInput, ok = input.(float64)
if !ok {
retInput, ok = input.(float32)
}
if !ok {
retInput, ok = input.(int)
}
if !ok {
retInput, ok = input.(int64)
}
if !ok {
retInput, ok = input.(int32)
}
if !ok {
Log.Warning("Could not convert %v OF TYPE %v to a number!! (tried float32, float64, int32, int64, int)", input, reflect.TypeOf(input))
} else {
Log.Debug("Number -> %v", reflect.TypeOf(input))
}
break
case String:
retInput, ok = input.(string)
break
case Bool:
retInput, ok = input.(bool)
break
case Time:
retInput, ok = input.(time.Time)
if !ok {
retInput, ok = input.(*time.Time)
}
break
}
// check if string
_, isString := input.(string)
if !ok && isString && rule.Type != String {
// try to convert a number/time/boolean string
Log.Debug("Trying to convert string (%v) to %v", input, rule.Type)
retInput = rule.convertString(input.(string))
if retInput != nil {
return rule.TypeOkFor(retInput)
}
}
return retInput, ok
}
/* * * * * * * * * * * * *
Helper Functions
* * * * * * * * * * * * */
func (rule *Rule) convertString(input string) interface{} {
Log.Debug("convertString <- %v", input)
var converted interface{}
var ok bool
var err error
switch rule.Type {
case Bool:
converted, err = strconv.ParseBool(input)
Log.Debug("Tried to convert bool '%v' to '%v': succeeded? %v", input, converted, err == nil)
if err != nil {
Log.Warning("Got error trying to convert '%v' to boolean:\n%v", input, err)
converted = nil
}
break
case Time:
converted, err = time.Parse(input, input)
timeConvert, _ := converted.(time.Time)
Log.Debug("GOT TIME CONVERT --> %v", timeConvert)
if timeConvert.Year() == 0 && timeConvert.Month() == 1 && timeConvert.Day() == 1 {
// reject a zero'd date (1/1/0000)
converted = nil
ok = false
}
break
case Int:
fallthrough
case Float:
fallthrough
case Number:
var num interface{}
var t int
num, t, ok = convertStringToNumber(input)
if !ok {
Log.Error("Could not convert string '%v' to number!", input)
} else {
switch t {
case Int:
converted = num.(int)
break
case Float:
converted = num.(float64)
break
}
Log.Debug("Converted %v to %v", input, converted)
}
break
}
Log.Debug("convertString -> %v, %v", converted, ok)
return converted
}
func convertStringToNumber(val string) (interface{}, int, bool) {
Log.Debug("convertStringToNumber <- %v", val)
var num interface{}
var t = 0
var ok = false
// first try to convert to float
for size := range []int{64, 32} { // try each size
float, err := strconv.ParseFloat(val, size)
if err == nil { // float success
num, t, ok = float, Float, true
} else { // try int
integer, err := strconv.ParseInt(val, 2, size)
if err == nil {
num, t, ok = integer, Int, true
}
}
}
Log.Debug("convertStringToNumber -> %v, %v, %v", num, t, ok)
return num, t, ok
}