From e135aff4a32a4714860759481459bffe2ea9ef15 Mon Sep 17 00:00:00 2001 From: fgy Date: Tue, 31 Oct 2023 14:24:37 +0800 Subject: [PATCH] optimize: prebind without content-length --- pkg/app/server/binding/binder_test.go | 27 +++++++++++++++++++++++++++ pkg/app/server/binding/default.go | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/pkg/app/server/binding/binder_test.go b/pkg/app/server/binding/binder_test.go index 2a66229c7..6db3a776a 100644 --- a/pkg/app/server/binding/binder_test.go +++ b/pkg/app/server/binding/binder_test.go @@ -1556,3 +1556,30 @@ func Benchmark_Binding(b *testing.B) { } } } + +func TestBind_BindProtobufWithoutContentLength(t *testing.T) { + data := testdata.HertzReq{Name: "hertz"} + body, err := proto.Marshal(&data) + if err != nil { + t.Fatal(err) + } + req := newMockRequest(). + SetRequestURI("http://foobar.com"). + SetProtobufContentType(). + SetBody(body) + + req.Req.Header.Del("Content-Length") + result := testdata.HertzReq{} + err = DefaultBinder().BindAndValidate(req.Req, &result, nil) + if err != nil { + t.Error(err) + } + assert.DeepEqual(t, "hertz", result.Name) + + result = testdata.HertzReq{} + err = DefaultBinder().BindProtobuf(req.Req, &result) + if err != nil { + t.Error(err) + } + assert.DeepEqual(t, "hertz", result.Name) +} diff --git a/pkg/app/server/binding/default.go b/pkg/app/server/binding/default.go index 0634f26cf..2aaa7ef52 100644 --- a/pkg/app/server/binding/default.go +++ b/pkg/app/server/binding/default.go @@ -319,7 +319,7 @@ func (b *defaultBinder) Bind(req *protocol.Request, v interface{}, params param. // best effort binding func (b *defaultBinder) preBindBody(req *protocol.Request, v interface{}) error { - if req.Header.ContentLength() <= 0 { + if len(req.Body()) == 0 { return nil } ct := bytesconv.B2s(req.Header.ContentType())