Add support for slices #1
					 2 changed files with 33 additions and 11 deletions
				
			
		
							
								
								
									
										36
									
								
								forms.go
									
										
									
									
									
								
							
							
						
						
									
										36
									
								
								forms.go
									
										
									
									
									
								
							|  | @ -70,19 +70,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 { | ||||
|  |  | |||
|  | @ -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) | ||||
|  |  | |||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue