feat: support float

bind
fgy 2023-01-05 12:30:11 +08:00
parent 7345517868
commit 081809e8a6
3 changed files with 42 additions and 0 deletions

View File

@ -497,3 +497,22 @@ func Benchmark_Bind(b *testing.B) {
}
}
}
func Test_Binder_Float(t *testing.T) {
t.Parallel()
app := New()
ctx := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
ctx.values = [maxParams]string{"3.14"}
ctx.route = &Route{Params: []string{"id"}}
var req struct {
ID1 float32 `param:"id"`
ID2 float64 `param:"id"`
}
err := ctx.Bind().Req(&req).Err()
require.NoError(t, err)
require.Equal(t, float32(3.14), req.ID1)
require.Equal(t, float64(3.14), req.ID2)
}

View File

@ -43,6 +43,10 @@ func CompileTextDecoder(rt reflect.Type) (TextDecoder, error) {
return &intDecoder{}, nil
case reflect.String:
return &stringDecoder{}, nil
case reflect.Float32:
return &floatDecoder{bitSize: 32}, nil
case reflect.Float64:
return &floatDecoder{bitSize: 64}, nil
}
return nil, errors.New("unsupported type " + rt.String())

19
internal/bind/float.go Normal file
View File

@ -0,0 +1,19 @@
package bind
import (
"reflect"
"strconv"
)
type floatDecoder struct {
bitSize int
}
func (d *floatDecoder) UnmarshalString(s string, fieldValue reflect.Value) error {
v, err := strconv.ParseFloat(s, d.bitSize)
if err != nil {
return err
}
fieldValue.SetFloat(v)
return nil
}