Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: customized type decode for binding #965

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion 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 @@ -526,7 +527,7 @@ type CustomizedDecode struct {

func TestBind_CustomizedTypeDecode(t *testing.T) {
type Foo struct {
F ***CustomizedDecode
F ***CustomizedDecode `query:"a"`
}

bindConfig := &BindConfig{}
Expand Down Expand Up @@ -1491,6 +1492,29 @@ func Test_ValidatorErrorFactory(t *testing.T) {
assert.DeepEqual(t, "validateErr: expr_path=[validateFailField]: B, cause=[validateErrMsg]: ", err.Error())
}

// Test_Issue964 used to the cover issue for time.Time
func Test_Issue964(t *testing.T) {
type CreateReq struct {
StartAt *time.Time `json:"startAt"`
}
r := newMockRequest().SetBody([]byte("{\n \"startAt\": \"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)
}
assert.DeepEqual(t, "2006-01-02 15:04:05 +0700 +0700", req.StartAt.String())
r = newMockRequest()
req = CreateReq{}
err = DefaultBinder().BindAndValidate(r.Req, &req, nil)
if err != nil {
t.Error(err)
}
if req.StartAt != nil {
t.Error("expected nil")
}
}

func Benchmark_Binding(b *testing.B) {
type Req struct {
Version string `path:"v"`
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 {
welkeyever marked this conversation as resolved.
Show resolved Hide resolved
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
welkeyever marked this conversation as resolved.
Show resolved Hide resolved
}

reqValue = GetFieldValue(reqValue, d.parentIndex)
field := reqValue.Field(d.index)
Expand Down