This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.go
88 lines (66 loc) · 1.56 KB
/
tag.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
package validator
import (
"bytes"
"encoding/json"
"reflect"
"strings"
)
func parseValidationTag(field reflect.StructField, tag string) *Validation {
value := &Validation{}
tagRunes := []rune(tag)
length := len(tagRunes)
buff := new(bytes.Buffer)
for i := 0; i <= length; i++ {
if i == length || tagRunes[i] == ';' {
parseValidationTagEntry(value, buff.String())
buff.Reset()
continue
}
buff.WriteRune(tagRunes[i])
}
sanitizeValidation(field, value)
return value
}
func parseValidationTagEntry(v *Validation, entry string) {
chunks := strings.SplitN(entry, ":", 2)
switch chunks[0] {
case "required":
parseValidationTagEntryOptionValue(&v.Options.Required, chunks)
case "email":
parseValidationTagEntryOptionValue(&v.Options.Email, chunks)
case "fieldName":
if len(chunks) == 2 {
v.Name = chunks[1]
}
}
}
func parseValidationTagEntryOptionValue(v *OptionValue, chunks []string) {
var err error
switch len(chunks) {
case 1:
v.Value = true
case 2:
chunks2 := strings.Split(chunks[1], "|")
for _, valueString := range chunks2 {
var value bool
err = json.Unmarshal([]byte(valueString), &value)
if err == nil {
v.Value = value
continue
}
prefix := "message="
if strings.HasPrefix(valueString, prefix) {
v.Message = strings.TrimPrefix(valueString, prefix)
}
}
}
}
func sanitizeValidation(field reflect.StructField, v *Validation) {
if v.Name == "" {
v.Name = field.Name
}
sanitizeOptions(field, &v.Options)
}
func sanitizeOptions(field reflect.StructField, opts *Options) {
// ...
}