From 081809e8a69649fafb59fa11dd629e9d00117a7a Mon Sep 17 00:00:00 2001 From: fgy Date: Thu, 5 Jan 2023 12:30:11 +0800 Subject: [PATCH] feat: support float --- bind_test.go | 19 +++++++++++++++++++ internal/bind/compile.go | 4 ++++ internal/bind/float.go | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 internal/bind/float.go diff --git a/bind_test.go b/bind_test.go index b94ba4d5..1dcd1b9e 100644 --- a/bind_test.go +++ b/bind_test.go @@ -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) +} diff --git a/internal/bind/compile.go b/internal/bind/compile.go index da5ca7ae..252afc6e 100644 --- a/internal/bind/compile.go +++ b/internal/bind/compile.go @@ -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()) diff --git a/internal/bind/float.go b/internal/bind/float.go new file mode 100644 index 00000000..300cbf7b --- /dev/null +++ b/internal/bind/float.go @@ -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 +}