-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
89 lines (76 loc) · 1.57 KB
/
config.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
package main
import (
"fmt"
"io/ioutil"
"strings"
"gopkg.in/yaml.v2"
)
func LoadFile(filename string) (*Config, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
cfg := &Config{}
err = yaml.Unmarshal(content, cfg)
if err != nil {
return nil, err
}
return cfg, nil
}
var (
DefaultModule = Module{
Port: 8080,
Proto: "http",
}
DefaultAuth = Auth{
Username: "",
Password: "",
}
)
type Config map[string]*Module
type Module struct {
Port int `yaml:"port"`
Proto string `yaml:"proto"`
Auth *Auth `yaml:"auth"`
XXX map[string]interface{} `yaml:",inline"`
}
func (c *Module) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultModule
type plain Module
if err := unmarshal((*plain)(c)); err != nil {
return err
}
if err := checkOverflow(c.XXX, "module"); err != nil {
return err
}
if c.Auth == nil {
c.Auth = &DefaultAuth
}
return nil
}
type Auth struct {
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
XXX map[string]interface{} `yaml:",inline"`
}
func (c *Auth) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultAuth
type plain Auth
if err := unmarshal((*plain)(c)); err != nil {
return err
}
if err := checkOverflow(c.XXX, "module"); err != nil {
return err
}
return nil
}
func checkOverflow(m map[string]interface{}, ctx string) error {
if len(m) > 0 {
var keys []string
for k := range m {
keys = append(keys, k)
}
return fmt.Errorf("unknown fields in %s: %s", ctx, strings.Join(keys, ", "))
}
return nil
}