-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatch.go
94 lines (67 loc) · 1.89 KB
/
dispatch.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
package configanywhere
import (
"errors"
"github.com/MatthewJWalls/configanywhere/formats"
"github.com/MatthewJWalls/configanywhere/providers"
)
// Dispatch and the convenience methods in this file
// allow us to support an API in the short format:
//
// configanywhere.Json(xs).FromFile(ys)
//
// which due to Go's lack of support for Traits means
// we have to do this somewhat clumsily as below.
type Provider interface {
GetBytes() ([]byte, error)
}
type Format interface {
Using([]byte)
}
type Dispatch struct {
F Format
}
// Convenience methods for providers
func (this Dispatch) FromProvider(p Provider) error {
bytes, err := p.GetBytes()
if err == nil {
this.F.Using(bytes)
}
return err
}
func (this Dispatch) FromFile(filename string) error {
return this.FromProvider(providers.NewFileProvider(filename))
}
func (this Dispatch) FromZookeeper(servers []string, nodePath string) error {
return this.FromProvider(providers.NewZookeeperProvider(servers, nodePath))
}
func (this Dispatch) FromString(text string) error {
return this.FromProvider(providers.NewStringProvider(text))
}
func (this Dispatch) FromEnvironment() error {
return this.FromProvider(providers.NewEnvironmentProvider())
}
// convenience methods for formats
func Json(target interface{}) Dispatch {
return Dispatch{ formats.NewJsonFormat(target) }
}
func KeyValue(target interface{}) Dispatch {
return Dispatch{ formats.NewKeyValueFormat(target) }
}
func XML(target interface{}) Dispatch {
return Dispatch{ formats.NewXMLFormat(target) }
}
func Yaml(target interface{}) Dispatch {
return Dispatch{ formats.NewYamlFormat(target) }
}
// other utils
func (this Dispatch) Choose(providers ...Provider) error {
for _, p := range providers {
if bytes, err := p.GetBytes(); err == nil {
this.F.Using(bytes)
return nil
} else {
continue
}
}
return errors.New("All providers returned an error")
}