-
Notifications
You must be signed in to change notification settings - Fork 351
/
validate.go
100 lines (89 loc) · 1.77 KB
/
validate.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
package validator
import (
"errors"
"fmt"
"regexp"
)
var (
ReValidRef = regexp.MustCompile(`^[^\s]+$`)
ReValidBranchID = regexp.MustCompile(`^\w[-\w]*$`)
ReValidRepositoryID = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{2,62}$`)
)
var (
ErrInvalid = errors.New("validation error")
ErrInvalidType = fmt.Errorf("invalid type: %w", ErrInvalid)
ErrRequiredValue = fmt.Errorf("required value: %w", ErrInvalid)
ErrInvalidValue = fmt.Errorf("invalid value: %w", ErrInvalid)
)
type ValidateFunc func(v interface{}) error
type ValidateArg struct {
Name string
Value interface{}
Fn ValidateFunc
}
type Secured interface {
SecureValue() string
}
func Validate(args []ValidateArg) error {
for _, arg := range args {
err := arg.Fn(arg.Value)
if err != nil {
return fmt.Errorf("argument %s: %w", arg.Name, err)
}
}
return nil
}
func MakeValidateOptional(fn ValidateFunc) ValidateFunc {
return func(v interface{}) error {
switch s := v.(type) {
case string:
if len(s) == 0 {
return nil
}
case Secured:
if len(s.SecureValue()) == 0 {
return nil
}
case fmt.Stringer:
if len(s.String()) == 0 {
return nil
}
case nil:
return nil
}
return fn(v)
}
}
func ValidateRequiredString(v interface{}) error {
s, ok := v.(string)
if !ok {
panic(ErrInvalidType)
}
if len(s) == 0 {
return ErrRequiredValue
}
return nil
}
func ValidateNonNegativeInt(v interface{}) error {
i, ok := v.(int)
if !ok {
panic(ErrInvalidType)
}
if i < 0 {
return ErrInvalidValue
}
return nil
}
func ValidateNilOrPositiveInt(v interface{}) error {
i, ok := v.(*int)
if !ok {
panic(ErrInvalidType)
}
if i == nil {
return nil
}
if *i <= 0 {
return fmt.Errorf("value should be greater than 0: %w", ErrInvalidValue)
}
return nil
}