-
Notifications
You must be signed in to change notification settings - Fork 44
/
parser.go
88 lines (70 loc) · 1.77 KB
/
parser.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
package cli
import (
"encoding/json"
"net/url"
)
// FlagParser represents a parser for parsing flag
type FlagParser interface {
Parse(s string) error
}
// FlagParserCreator represents factory function of FlagParser
type FlagParserCreator func(ptr interface{}) FlagParser
var parserCreators = map[string]FlagParserCreator{}
// RegisterFlagParser registers FlagParserCreator by name
func RegisterFlagParser(name string, creator FlagParserCreator) {
if _, ok := parserCreators[name]; ok {
panic("RegisterFlagParser has registered: " + name)
}
parserCreators[name] = creator
}
func init() {
RegisterFlagParser("json", newJSONParser)
RegisterFlagParser("jsonfile", newJSONFileParser)
RegisterFlagParser("jsoncfg", newJSONConfigFileParser)
RegisterFlagParser("url", newURLParser)
}
// JSON parser
type JSONParser struct {
ptr interface{}
}
func newJSONParser(ptr interface{}) FlagParser {
return &JSONParser{ptr}
}
func (p JSONParser) Parse(s string) error {
return json.Unmarshal([]byte(s), p.ptr)
}
// JSON file parser
type JSONFileParser struct {
ptr interface{}
}
func newJSONFileParser(ptr interface{}) FlagParser {
return &JSONFileParser{ptr}
}
func (p JSONFileParser) Parse(s string) error {
return ReadJSONFromFile(s, p.ptr)
}
// JSON config file parser
type JSONConfigFileParser struct {
ptr interface{}
}
func newJSONConfigFileParser(ptr interface{}) FlagParser {
return &JSONConfigFileParser{ptr}
}
func (p JSONConfigFileParser) Parse(s string) error {
return ReadJSONConfigFromFile(s, p.ptr)
}
// URL parser
type URLParser struct {
ptr *url.URL
}
func newURLParser(ptr interface{}) FlagParser {
return &URLParser{ptr: ptr.(*url.URL)}
}
func (p *URLParser) Parse(s string) error {
u, err := url.Parse(s)
if err != nil {
return err
}
*p.ptr = *u
return nil
}