mirror of https://github.com/gofiber/fiber.git
feat: support float
parent
7345517868
commit
081809e8a6
19
bind_test.go
19
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)
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue