/
filtered_string.go
92 lines (72 loc) · 1.55 KB
/
filtered_string.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
package types
import (
"encoding/json"
"strings"
)
// FilteredString is a wrapper around string values that can be null/default or an
// actual value. Use IsSet to check if the value is provided, instead of
// checking against the empty string.
type FilteredString struct {
IsSet bool
Value string
}
type FilteredStrings []FilteredString
func NewFilteredString(val string) *FilteredString {
var result FilteredString
result.ParseValue(val)
return &result
}
// ParseValue is used to parse a user provided flag argument.
func (n *FilteredString) ParseValue(val string) {
if val == "" {
n.IsSet = false
n.Value = ""
return
}
n.IsSet = true
switch val {
case "null", "default":
n.Value = ""
default:
n.Value = val
}
}
func (n FilteredString) IsDefault() bool {
return n.IsSet && n.Value == ""
}
func (n *FilteredString) UnmarshalJSON(rawJSON []byte) error {
var value *string
err := json.Unmarshal(rawJSON, &value)
if err != nil {
return err
}
if value != nil {
n.Value = *value
n.IsSet = true
return nil
}
n.Value = ""
n.IsSet = false
return nil
}
// MarshalJSON marshals the value field if it's not empty, otherwise returns an
// null.
func (n FilteredString) MarshalJSON() ([]byte, error) {
if n.Value != "" {
return json.Marshal(n.Value)
}
return json.Marshal(new(json.RawMessage))
}
func (n FilteredString) String() string {
if n.IsSet {
return n.Value
}
return ""
}
func (n FilteredStrings) String() string {
var ss []string
for _, fs := range n {
ss = append(ss, fs.Value)
}
return strings.Join(ss, ", ")
}