-
Notifications
You must be signed in to change notification settings - Fork 4
/
json.go
62 lines (53 loc) · 1.25 KB
/
json.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
package flagvar
import (
"encoding/json"
"strings"
)
// JSON is a `flag.Value` for JSON arguments.
type JSON struct {
Value interface{}
Text string
}
// Help returns a string suitable for inclusion in a flag help message.
func (fv *JSON) Help() string {
return "a JSON value"
}
// Set is flag.Value.Set
func (fv *JSON) Set(v string) error {
fv.Text = v
if fv.Value == nil {
return json.Unmarshal([]byte(v), &fv.Value)
}
return json.Unmarshal([]byte(v), fv.Value)
}
func (fv *JSON) String() string {
return fv.Text
}
// JSONs is a `flag.Value` for JSON arguments. If non-nil, the `Value` field is used to generate template values.
type JSONs struct {
Value func() interface{}
Values []interface{}
Texts []string
}
// Help returns a string suitable for inclusion in a flag help message.
func (fv *JSONs) Help() string {
return "a JSON value"
}
// Set is flag.Value.Set
func (fv *JSONs) Set(v string) (err error) {
var value interface{}
if fv.Value != nil {
value = fv.Value()
err = json.Unmarshal([]byte(v), value)
} else {
err = json.Unmarshal([]byte(v), &value)
}
if err == nil {
fv.Texts = append(fv.Texts, v)
fv.Values = append(fv.Values, value)
}
return err
}
func (fv *JSONs) String() string {
return strings.Join(fv.Texts, ",")
}