From d8ef3f68a4c0e491938b5419a7fc31a2cfc088e1 Mon Sep 17 00:00:00 2001 From: liqiang2 Date: Sun, 25 Oct 2026 15:29:16 +0800 Subject: [PATCH] fix(binding): accept named byte slices in plain body binding --- binding/binding_test.go | 11 +++++++++++ binding/plain.go | 2 +- context_test.go | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/binding/binding_test.go b/binding/binding_test.go index f90488cd..90f74816 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -1403,6 +1403,17 @@ func TestPlainBinding(t *testing.T) { require.NoError(t, p.Bind(req, ptr)) } +func TestPlainBindingNamedBytes(t *testing.T) { + data := []byte(`{"message":"raw body"}`) + var body json.RawMessage + require.NoError(t, Plain.Bind(requestWithBody(http.MethodPost, "/", string(data)), &body)) + assert.Equal(t, data, []byte(body)) + + body = nil + require.NoError(t, Plain.BindBody(data, &body)) + assert.Equal(t, data, []byte(body)) +} + func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, name, b.Name()) diff --git a/binding/plain.go b/binding/plain.go index 5d466bdd..ae6be54c 100644 --- a/binding/plain.go +++ b/binding/plain.go @@ -47,7 +47,7 @@ func decodePlain(data []byte, obj any) error { return nil } - if _, ok := v.Interface().([]byte); ok { + if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 { v.SetBytes(data) return nil } diff --git a/context_test.go b/context_test.go index b82e04d5..108355a1 100644 --- a/context_test.go +++ b/context_test.go @@ -2598,6 +2598,24 @@ func TestContextShouldBindPlain(t *testing.T) { assert.Equal(t, 0, w.Body.Len()) } +func TestContextShouldBindPlainNamedBytes(t *testing.T) { + type bodyBytes []byte + data := []byte{'a', 0, 0xff, 'z'} + router := New() + router.POST("/", func(c *Context) { + var body bodyBytes + if err := c.ShouldBindPlain(&body); err != nil { + c.String(http.StatusBadRequest, "%s", err) + return + } + c.Data(http.StatusOK, "application/octet-stream", []byte(body)) + }) + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(data))) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, data, w.Body.Bytes()) +} + func TestContextShouldBindHeader(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w)