-
Notifications
You must be signed in to change notification settings - Fork 0
/
structtag.go
72 lines (57 loc) · 1.28 KB
/
structtag.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"
"sort"
"strconv"
"strings"
)
// StructTag represents a struct tag.
type StructTag interface {
Set(key, val string)
Get(key string) (string, bool)
Keys() []string
String() string
}
type structTagImpl map[string]string
// FromMap creates a new StructTag.
func FromMap(m map[string]string) StructTag {
return structTagImpl(m)
}
// Union creates a new StructTag with all keys from a and b.
// Values for keys in a will be overwritten if set in b.
func Union(a, b StructTag) StructTag {
tag := structTagImpl(map[string]string{})
tag.append(a)
tag.append(b)
return tag
}
func (t structTagImpl) Set(key, val string) {
t[key] = val
}
func (t structTagImpl) Get(key string) (string, bool) {
val, ok := t[key]
return val, ok
}
func (t structTagImpl) Keys() []string {
keys := []string{}
for key := range t {
keys = append(keys, key)
}
// Ensure reproducible ordering
sort.Strings(keys)
return keys
}
func (t structTagImpl) String() string {
s := []string{}
for _, key := range t.Keys() {
val := strconv.Quote(t[key])
s = append(s, fmt.Sprintf("%s:%s", key, val))
}
return fmt.Sprintf("`%s`", strings.Join(s, " "))
}
func (t structTagImpl) append(tag StructTag) {
for _, key := range tag.Keys() {
val, _ := tag.Get(key)
t.Set(key, val)
}
}