-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
72 lines (60 loc) · 1.37 KB
/
parse.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
package structtag
import (
"fmt"
"strconv"
"strings"
)
// Parse parses a string representing a struct tag.
func Parse(s string) (StructTag, error) {
t := FromMap(map[string]string{})
orig := s
s = normalize(s)
// This code is based on reflect.StructTag.Lookup
i := 0
for i < len(s) {
// Skip leading space.
j := i
for j < len(s) && s[j] == ' ' {
j++
}
if j >= len(s) {
break
}
// Scan to colon.
i = j
for j < len(s) && s[j] > ' ' && s[j] != ':' && s[j] != '"' && s[j] != 0x7f {
j++
}
if j == i || j+1 >= len(s) || s[j] != ':' || s[j+1] != '"' {
return nil, fmt.Errorf("invalid key in pair in struct tag: %s:%d-%d", orig, i, j)
}
key := string(s[i:j])
j++ // move past colon
// Scan quoted string to find value.
i = j
j++ // move past beg quote
for j < len(s) && s[j] != '"' {
if s[j] == '\\' {
j++
}
j++
}
if j >= len(s) {
return nil, fmt.Errorf("invalid value in pair in struct tag: %s:%d-%d, key: %s", orig, i, j, key)
}
j++ // move to end quote
qval := string(s[i:j])
val, err := strconv.Unquote(qval)
if err != nil {
return nil, fmt.Errorf("invald value in pair in struct tag: %s:%d-%d, key: %s, val: %s, err: %v", orig, i, j, key, qval, err)
}
t.Set(key, val)
j++ // move past end quote
i = j
}
return t, nil
}
func normalize(s string) string {
s = strings.Trim(s, "`")
return s
}