Merge pull request #78 from filoozom/patch-1

Update config.go to handle default slices correctly (fixes #76)
This commit is contained in:
Jakob Borg 2014-03-04 15:09:47 +01:00
commit 2d0600de38

View File

@ -46,7 +46,7 @@ type OptionsConfiguration struct {
MaxChangeKbps int `xml:"maxChangeKbps" default:"1000" ini:"max-change-bw"` MaxChangeKbps int `xml:"maxChangeKbps" default:"1000" ini:"max-change-bw"`
} }
func setDefaults(data interface{}) error { func setDefaults(data interface{}, setEmptySlices bool) error {
s := reflect.ValueOf(data).Elem() s := reflect.ValueOf(data).Elem()
t := s.Type() t := s.Type()
@ -56,14 +56,20 @@ func setDefaults(data interface{}) error {
v := tag.Get("default") v := tag.Get("default")
if len(v) > 0 { if len(v) > 0 {
if f.Kind().String() == "slice" && f.Len() != 0 {
continue
}
switch f.Interface().(type) { switch f.Interface().(type) {
case string: case string:
f.SetString(v) f.SetString(v)
case []string: case []string:
rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1) if setEmptySlices {
rv.Index(0).SetString(v) rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
f.Set(rv) rv.Index(0).SetString(v)
f.Set(rv)
}
case int: case int:
i, err := strconv.ParseInt(v, 10, 64) i, err := strconv.ParseInt(v, 10, 64)
@ -146,14 +152,16 @@ func uniqueStrings(ss []string) []string {
func readConfigXML(rd io.Reader) (Configuration, error) { func readConfigXML(rd io.Reader) (Configuration, error) {
var cfg Configuration var cfg Configuration
setDefaults(&cfg) setDefaults(&cfg, false)
setDefaults(&cfg.Options) setDefaults(&cfg.Options, false)
var err error var err error
if rd != nil { if rd != nil {
err = xml.NewDecoder(rd).Decode(&cfg) err = xml.NewDecoder(rd).Decode(&cfg)
} }
setDefaults(&cfg.Options, true)
cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress) cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
return cfg, err return cfg, err
} }