From 97e6e7c6ca70115445754ff9a51897546e2a0b98 Mon Sep 17 00:00:00 2001 From: fgy Date: Wed, 27 Sep 2023 16:38:08 +0800 Subject: [PATCH] fix: customized type decode --- pkg/app/server/binding/binder_test.go | 14 ++++++++++++++ pkg/app/server/binding/config.go | 2 +- .../internal/decoder/customized_type_decoder.go | 6 ++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/app/server/binding/binder_test.go b/pkg/app/server/binding/binder_test.go index c971776e3..9f21734e1 100644 --- a/pkg/app/server/binding/binder_test.go +++ b/pkg/app/server/binding/binder_test.go @@ -47,6 +47,7 @@ import ( "net/url" "reflect" "testing" + "time" "github.com/cloudwego/hertz/pkg/app/server/binding/testdata" "github.com/cloudwego/hertz/pkg/common/test/assert" @@ -1491,6 +1492,19 @@ func Test_ValidatorErrorFactory(t *testing.T) { assert.DeepEqual(t, "validateErr: expr_path=[validateFailField]: B, cause=[validateErrMsg]: ", err.Error()) } +func Test_BindTime(t *testing.T) { + type CreateReq struct { + StartAt *time.Time `json:"startAt"` + } + r := newMockRequest().SetBody([]byte("{\n \"startsAt\": \"2006-01-02T15:04:05+07:00\"\n}")).SetJSONContentType() + var req CreateReq + err := DefaultBinder().BindAndValidate(r.Req, &req, nil) + if err != nil { + t.Error(err) + } + fmt.Println(req) +} + func Benchmark_Binding(b *testing.B) { type Req struct { Version string `path:"v"` diff --git a/pkg/app/server/binding/config.go b/pkg/app/server/binding/config.go index 81cf30e56..55d730f43 100644 --- a/pkg/app/server/binding/config.go +++ b/pkg/app/server/binding/config.go @@ -112,7 +112,7 @@ func (config *BindConfig) MustRegTypeUnmarshal(t reflect.Type, fn func(req *prot func (config *BindConfig) initTypeUnmarshal() { config.MustRegTypeUnmarshal(reflect.TypeOf(time.Time{}), func(req *protocol.Request, params param.Params, text string) (reflect.Value, error) { - if text == "" { + if text == "" && config.LooseZeroMode { return reflect.ValueOf(time.Time{}), nil } t, err := time.Parse(time.RFC3339, text) diff --git a/pkg/app/server/binding/internal/decoder/customized_type_decoder.go b/pkg/app/server/binding/internal/decoder/customized_type_decoder.go index 8bf0f0121..19efa46ae 100644 --- a/pkg/app/server/binding/internal/decoder/customized_type_decoder.go +++ b/pkg/app/server/binding/internal/decoder/customized_type_decoder.go @@ -69,6 +69,9 @@ func (d *customizedFieldTextDecoder) Decode(req *protocol.Request, params param. break } } + if !exist { + return nil + } if len(text) == 0 && len(defaultValue) != 0 { text = defaultValue } @@ -77,6 +80,9 @@ func (d *customizedFieldTextDecoder) Decode(req *protocol.Request, params param. if err != nil { return err } + if !v.IsValid() { + return nil + } reqValue = GetFieldValue(reqValue, d.parentIndex) field := reqValue.Field(d.index)