From cb820957696d4e901d854cb452583d3e8e2f2b28 Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Sat, 23 May 2026 22:42:33 +0800 Subject: [PATCH 1/2] feat(context): add ShouldBindBodyWithProtoBuf shortcut --- context.go | 5 +++++ context_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/context.go b/context.go index 5174033e..451bda98 100644 --- a/context.go +++ b/context.go @@ -967,6 +967,11 @@ func (c *Context) ShouldBindBodyWithPlain(obj any) error { return c.ShouldBindBodyWith(obj, binding.Plain) } +// ShouldBindBodyWithProtoBuf is a shortcut for c.ShouldBindBodyWith(obj, binding.ProtoBuf). +func (c *Context) ShouldBindBodyWithProtoBuf(obj any) error { + return c.ShouldBindBodyWith(obj, binding.ProtoBuf) +} + // ClientIP implements one best effort algorithm to return the real client IP. // It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. // If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-IP]). diff --git a/context_test.go b/context_test.go index ef60379d..860aa0a2 100644 --- a/context_test.go +++ b/context_test.go @@ -2916,6 +2916,21 @@ func TestContextShouldBindBodyWithPlain(t *testing.T) { } } +func TestContextShouldBindBodyWithProtoBuf(t *testing.T) { + label := "FOO" + protoBody, err := proto.Marshal(&testdata.Test{Label: &label}) + require.NoError(t, err) + + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(protoBody)) + + obj := testdata.Test{} + require.NoError(t, c.ShouldBindBodyWithProtoBuf(&obj)) + require.NotNil(t, obj.Label) + assert.Equal(t, "FOO", *obj.Label) +} + func TestContextGolangContext(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`)) From e83cdcc9e463ec5d582123e34ecb602a3b46c6c5 Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Sat, 23 May 2026 22:47:06 +0800 Subject: [PATCH 2/2] docs: document ShouldBindBodyWithProtoBuf shortcut --- docs/doc.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/doc.md b/docs/doc.md index d1c33b87..addfaef9 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -1576,6 +1576,7 @@ For this, you can use `c.ShouldBindBodyWith` or shortcuts. - `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML). - `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML). - `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML). +- `c.ShouldBindBodyWithProtoBuf` is a shortcut for c.ShouldBindBodyWith(obj, binding.ProtoBuf). ```go func SomeHandler(c *gin.Context) {