Add support for slices

This commit is contained in:
Elwin Tamminga 2019-10-01 16:08:20 +02:00 committed by NiseVoid
parent 122175c75b
commit 056b574ce1
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3
2 changed files with 33 additions and 11 deletions

View File

@ -79,19 +79,33 @@ func decode(form Values, rv reflect.Value, prefix string) {
}
}
func setValue(v []string, fv reflect.Value) {
switch f := fv.Interface().(type) {
case *string:
*f = v[0]
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)
func setValue(values []string, fv reflect.Value) {
if fv.Elem().Type().Kind() != reflect.Slice {
parse(values[0], fv)
return
}
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 {

View File

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