forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtag.go
131 lines (112 loc) · 2.46 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
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
package influxdb
import (
"encoding/json"
"regexp"
"strings"
)
// Operator is an Enum value of operators.
type Operator int
// Valid returns invalid error if the operator is invalid.
func (op Operator) Valid() error {
if op < Equal || op > NotRegexEqual {
return &Error{
Code: EInvalid,
Msg: "Operator is invalid",
}
}
return nil
}
// operators
const (
Equal Operator = iota
NotEqual
RegexEqual
NotRegexEqual
)
var opStr = []string{
"equal",
"notequal",
"equalregex",
"notequalregex",
}
var opStrMap = map[string]Operator{
"equal": Equal,
"notequal": NotEqual,
"equalregex": RegexEqual,
"notequalregex": NotRegexEqual,
}
// String returns the string value of the operator.
func (op Operator) String() string {
if err := op.Valid(); err != nil {
return ""
}
return opStr[op]
}
// MarshalJSON implements json.Marshal interface.
func (op Operator) MarshalJSON() ([]byte, error) {
return json.Marshal(op.String())
}
// UnmarshalJSON implements json.Unmarshaler interface.
func (op *Operator) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return &Error{
Code: EInvalid,
Err: err,
}
}
var ok bool
if *op, ok = opStrMap[s]; !ok {
return &Error{
Code: EInvalid,
Msg: "unrecognized operator",
}
}
return nil
}
// Tag is a tag key-value pair.
type Tag struct {
Key string `json:"key"`
Value string `json:"value"`
}
// NewTag generates a tag pair from a string in the format key:value.
func NewTag(s string) (Tag, error) {
var tagPair Tag
matched, err := regexp.MatchString(`^[a-zA-Z0-9_]+:[a-zA-Z0-9_]+$`, s)
if !matched || err != nil {
return tagPair, &Error{
Code: EInvalid,
Msg: `tag must be in form key:value`,
}
}
slice := strings.Split(s, ":")
tagPair.Key = slice[0]
tagPair.Value = slice[1]
return tagPair, nil
}
// Valid returns an error if the tagpair is missing fields
func (t Tag) Valid() error {
if t.Key == "" || t.Value == "" {
return &Error{
Code: EInvalid,
Msg: "tag must contain a key and a value",
}
}
return nil
}
// QueryParam converts a Tag to a string query parameter
func (t *Tag) QueryParam() string {
return strings.Join([]string{t.Key, t.Value}, ":")
}
// TagRule is the struct of tag rule.
type TagRule struct {
Tag
Operator Operator `json:"operator"`
}
// Valid returns error for invalid operators.
func (tr TagRule) Valid() error {
if err := tr.Tag.Valid(); err != nil {
return err
}
return tr.Operator.Valid()
}