Skip to content

Commit

Permalink
fix: customized type decode
Browse files Browse the repository at this point in the history
  • Loading branch information
FGYFFFF committed Sep 27, 2023
1 parent 7698012 commit 97e6e7c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
14 changes: 14 additions & 0 deletions pkg/app/server/binding/binder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"`
Expand Down
2 changes: 1 addition & 1 deletion pkg/app/server/binding/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
Expand Down

0 comments on commit 97e6e7c

Please sign in to comment.