Update config.go to handle default slices correctly

This commit is contained in:
filoozom 2014-03-04 11:25:10 +01:00
parent ba59e0d3f0
commit 428164f395

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{}, setNilSlices bool) error {
s := reflect.ValueOf(data).Elem() s := reflect.ValueOf(data).Elem()
t := s.Type() t := s.Type()
@ -56,14 +56,21 @@ 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 {
fmt.Println(f.Type(), f.Type().Kind().String(), f.Len())
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 setNilSlices {
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 +153,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
} }