Add support for slices #1

Closed
elwint wants to merge 1 commits from (deleted):master into master
2 changed files with 33 additions and 11 deletions

View File

@ -70,19 +70,33 @@ func decode(form Values, rv reflect.Value, prefix string) {
} }
} }
func setValue(v []string, fv reflect.Value) { func setValue(values []string, fv reflect.Value) {
switch f := fv.Interface().(type) { if fv.Elem().Type().Kind() != reflect.Slice {
case *string: parse(values[0], fv)
*f = v[0] return
case *int:
*f, _ = strconv.Atoi(v[0])
case *float32:
v, _ := strconv.ParseFloat(v[0], 32)
*f = float32(v)
case *float64:
*f, _ = strconv.ParseFloat(v[0], 64)
} }
slice := reflect.MakeSlice(fv.Elem().Type(), len(values), len(values))
val := reflect.New(slice.Type().Elem())
for i, v := range values {
parse(v, val)
slice.Index(i).Set(val.Elem())
}
fv.Elem().Set(slice)
}
func parse(v string, fv reflect.Value) {
switch f := fv.Interface().(type) {
case *string:
*f = v
case *int:
*f, _ = strconv.Atoi(v)
case *float32:
v, _ := strconv.ParseFloat(v, 32)
*f = float32(v)
case *float64:
*f, _ = strconv.ParseFloat(v, 64)
}
} }
func getPrefix(ft reflect.StructField, prefix string) string { func getPrefix(ft reflect.StructField, prefix string) string {

View File

@ -15,6 +15,10 @@ type testStruct struct {
PA *string PA *string
PD *nested PD *nested
SA []string
SB []int
SC []float64
} }
type nested struct { type nested struct {
@ -46,6 +50,10 @@ func TestDecode(t *testing.T) {
`PD.A`: {`test5`}, `PD.A`: {`test5`},
`PD.B`: {`30`}, `PD.B`: {`30`},
`PD.C`: {`3.75`}, `PD.C`: {`3.75`},
`SA`: {`test6`, `slice`},
`SB`: {`3`, `2`},
`SC`: {`4.50`, `1.32`},
}, data) }, data)
fmt.Println(`data:`, data, *data.PA, *data.PD) fmt.Println(`data:`, data, *data.PA, *data.PD)