Skip to content
Myr

feat(render): add bson protocol (#4145)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Laurent Caumont · committed by GitHub · parent e3118cc · Browse files · 10 files+162 added−11 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+162 added−11 removed

  • other:+162 added−11 removed

10 files+162 added−11 removed

modified:binding/binding_nomsgpack.go+4 added
19 unmodified lines
20 MIMEPROTOBUF = "application/x-protobuf"21 MIMEYAML = "application/x-yaml"22 MIMEYAML2 = "application/yaml"23 MIMETOML = "application/toml"24 MIMEBSON = "application/bson"25)2627// Binding describes the interface which needs to be implemented for binding the28// data present in the request such as JSON request body, query parameters or
53 unmodified lines
82 Uri = uriBinding{}83 Header = headerBinding{}84 TOML = tomlBinding{}85 Plain = plainBinding{}86 BSON BindingBody = bsonBinding{}87)8889// Default returns the appropriate Binding instance based on the HTTP method90// and the content type.
14 unmodified lines
105 case MIMEMultipartPOSTForm:106 return FormMultipart107 case MIMETOML:108 return TOML109 case MIMEBSON:110 return BSON111 default: // case MIMEPOSTForm:112 return Form113 }114}
7 unmodified lines
modified:binding/binding_test.go+16 added
19 unmodified lines
2021 "github.com/gin-gonic/gin/testdata/protoexample"22 "github.com/stretchr/testify/assert"23 "github.com/stretchr/testify/require"24 "go.mongodb.org/mongo-driver/bson"25 "google.golang.org/protobuf/proto"26)2728type appkey struct {
143 unmodified lines
172 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML2))173174 assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))175 assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))176177 assert.Equal(t, BSON, Default(http.MethodPost, MIMEBSON))178 assert.Equal(t, BSON, Default(http.MethodPut, MIMEBSON))179}180181func TestBindingJSONNilBody(t *testing.T) {182 var obj FooStruct
551 unmodified lines
734 "/", "/",735 string(data), string(data[1:]))736}737738func TestBindingBSON(t *testing.T) {739 var obj FooStruct740 obj.Foo = "bar"741 data, _ := bson.Marshal(&obj)742 testBodyBinding(t,743 BSON, "bson",744 "/", "/",745 string(data),746 // note: for badbody, we remove first byte to make it invalid747 string(data[1:]))748}749750func TestValidationFails(t *testing.T) {751 var obj FooStruct752 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)753 err := JSON.Bind(req, &obj)
681 unmodified lines
modified:binding/binding.go+4 added
21 unmodified lines
22 MIMEMSGPACK2 = "application/msgpack"23 MIMEYAML = "application/x-yaml"24 MIMEYAML2 = "application/yaml"25 MIMETOML = "application/toml"26 MIMEBSON = "application/bson"27)2829// Binding describes the interface which needs to be implemented for binding the30// data present in the request such as JSON request body, query parameters or
55 unmodified lines
86 Uri BindingUri = uriBinding{}87 Header Binding = headerBinding{}88 Plain BindingBody = plainBinding{}89 TOML BindingBody = tomlBinding{}90 BSON BindingBody = bsonBinding{}91)9293// Default returns the appropriate Binding instance based on the HTTP method94// and the content type.
16 unmodified lines
111 case MIMETOML:112 return TOML113 case MIMEMultipartPOSTForm:114 return FormMultipart115 case MIMEBSON:116 return BSON117 default: // case MIMEPOSTForm:118 return Form119 }120}
7 unmodified lines
added:binding/bson.go+30 added
1// Copyright 2025 Gin Core Team. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (8 "io"9 "net/http"1011 "go.mongodb.org/mongo-driver/bson"12)1314type bsonBinding struct{}1516func (bsonBinding) Name() string {17 return "bson"18}1920func (b bsonBinding) Bind(req *http.Request, obj any) error {21 buf, err := io.ReadAll(req.Body)22 if err == nil {23 err = b.BindBody(buf, obj)24 }25 return err26}2728func (bsonBinding) BindBody(body []byte, obj any) error {29 return bson.Unmarshal(body, obj)30}
added:render/bson.go+34 added
1// Copyright 2025 Gin Core Team. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package render67import (8 "net/http"910 "go.mongodb.org/mongo-driver/bson"11)1213// BSON contains the given interface object.14type BSON struct {15 Data any16}1718var bsonContentType = []string{"application/bson"}1920// Render (BSON) marshals the given interface object and writes data with custom ContentType.21func (r BSON) Render(w http.ResponseWriter) error {22 r.WriteContentType(w)2324 bytes, err := bson.Marshal(&r.Data)25 if err == nil {26 _, err = w.Write(bytes)27 }28 return err29}3031// WriteContentType (BSONBuf) writes BSONBuf ContentType.32func (r BSON) WriteContentType(w http.ResponseWriter) {33 writeContentType(w, bsonContentType)34}
modified:render/render_test.go+26 added
17 unmodified lines
18 "github.com/gin-gonic/gin/codec/json"19 testdata "github.com/gin-gonic/gin/testdata/protoexample"20 "github.com/stretchr/testify/assert"21 "github.com/stretchr/testify/require"22 "go.mongodb.org/mongo-driver/bson"23 "google.golang.org/protobuf/proto"24)2526// TODO unit tests
332 unmodified lines
359 err := (ProtoBuf{data}).Render(w)360 require.Error(t, err)361}362363func TestRenderBSON(t *testing.T) {364 w := httptest.NewRecorder()365 reps := []int64{int64(1), int64(2)}366 type mystruct struct {367 Label string368 Reps []int64369 }370371 data := &mystruct{372 Label: "test",373 Reps: reps,374 }375376 (BSON{data}).WriteContentType(w)377 bsonData, err := bson.Marshal(data)378 require.NoError(t, err)379 assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))380381 err = (BSON{data}).Render(w)382383 require.NoError(t, err)384 assert.Equal(t, bsonData, w.Body.Bytes())385 assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))386}387388func TestRenderXML(t *testing.T) {389 w := httptest.NewRecorder()390 data := xmlmap{391 "foo": "bar",
263 unmodified lines
modified:context_test.go+18 added
30 unmodified lines
31 "github.com/gin-gonic/gin/codec/json"32 testdata "github.com/gin-gonic/gin/testdata/protoexample"33 "github.com/stretchr/testify/assert"34 "github.com/stretchr/testify/require"35 "go.mongodb.org/mongo-driver/bson"36 "google.golang.org/protobuf/proto"37)3839var _ context.Context = (*Context)(nil)
1661 unmodified lines
1701 assert.Equal(t, string(protoData), w.Body.String())1702 assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))1703}17041705func TestContextNegotiationWithBSON(t *testing.T) {1706 w := httptest.NewRecorder()1707 c, _ := CreateTestContext(w)1708 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)17091710 c.Negotiate(http.StatusOK, Negotiate{1711 Offered: []string{MIMEBSON, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1712 Data: H{"foo": "bar"},1713 })17141715 bData, _ := bson.Marshal(H{"foo": "bar"})17161717 assert.Equal(t, http.StatusOK, w.Code)1718 assert.Equal(t, string(bData), w.Body.String())1719 assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))1720}17211722func TestContextNegotiationNotSupport(t *testing.T) {1723 w := httptest.NewRecorder()1724 c, _ := CreateTestContext(w)1725 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)
2029 unmodified lines
modified:context.go+11 added
38 unmodified lines
39 MIMEYAML = binding.MIMEYAML40 MIMEYAML2 = binding.MIMEYAML241 MIMETOML = binding.MIMETOML42 MIMEPROTOBUF = binding.MIMEPROTOBUF43 MIMEBSON = binding.MIMEBSON44)4546// BodyBytesKey indicates a default body bytes key.47const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
1189 unmodified lines
1237func (c *Context) ProtoBuf(code int, obj any) {1238 c.Render(code, render.ProtoBuf{Data: obj})1239}12401241// BSON serializes the given struct as BSON into the response body.1242func (c *Context) BSON(code int, obj any) {1243 c.Render(code, render.BSON{Data: obj})1244}12451246// String writes the given string into the response body.1247func (c *Context) String(code int, format string, values ...any) {1248 c.Render(code, render.String{Format: format, Data: values})1249}
99 unmodified lines
1349 YAMLData any1350 Data any1351 TOMLData any1352 PROTOBUFData any1353 BSONData any1354}13551356// Negotiate calls different Render according to acceptable Accept format.1357func (c *Context) Negotiate(code int, config Negotiate) {
21 unmodified lines
1379 case binding.MIMEPROTOBUF:1380 data := chooseData(config.PROTOBUFData, config.Data)1381 c.ProtoBuf(code, data)13821383 case binding.MIMEBSON:1384 data := chooseData(config.BSONData, config.Data)1385 c.BSON(code, data)13861387 default:1388 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck1389 }1390}
92 unmodified lines
modified:go.mod+9 added-4 removed
1module github.com/gin-gonic/gin23go 1.24.045toolchain go1.24.767require (8 github.com/bytedance/sonic v1.14.29 github.com/gin-contrib/sse v1.1.010 github.com/go-playground/validator/v10 v10.28.09 github.com/goccy/go-json v0.10.211 github.com/goccy/go-json v0.10.512 github.com/goccy/go-yaml v1.19.113 github.com/json-iterator/go v1.1.1214 github.com/mattn/go-isatty v0.0.2015 github.com/modern-go/reflect2 v1.0.216 github.com/pelletier/go-toml/v2 v2.2.417 github.com/quic-go/quic-go v0.57.118 github.com/stretchr/testify v1.11.119 github.com/ugorji/go/codec v1.3.120 go.mongodb.org/mongo-driver v1.17.721 golang.org/x/net v0.47.022 google.golang.org/protobuf v1.36.1023)2425require gopkg.in/yaml.v3 v3.0.1 // indirect2627require (28 github.com/bytedance/gopkg v0.1.3 // indirect29 github.com/bytedance/sonic/loader v0.4.0 // indirect30 github.com/cloudwego/base64x v0.1.6 // indirect
3 unmodified lines
34 github.com/go-playground/universal-translator v0.18.1 // indirect35 github.com/klauspost/cpuid/v2 v2.3.0 // indirect36 github.com/kr/text v0.2.0 // indirect37 github.com/leodido/go-urn v1.4.0 // indirect33 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect38 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect39 github.com/pmezard/go-difflib v1.0.0 // indirect40 github.com/quic-go/qpack v0.6.0 // indirect41 github.com/twitchyliquid64/golang-asm v0.15.1 // indirect42 go.uber.org/mock v0.6.0 // indirect37 golang.org/x/arch v0.20.0 // indirect43 golang.org/x/arch v0.22.0 // indirect44 golang.org/x/crypto v0.45.0 // indirect45 golang.org/x/sys v0.38.0 // indirect46 golang.org/x/text v0.31.0 // indirect41 gopkg.in/yaml.v3 v3.0.1 // indirect47)
modified:go.sum+10 added-7 removed
20 unmodified lines
21github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=22github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=23github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=24github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=25github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=26github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=25github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=26github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=27github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE=28github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=29github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=30github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
9 unmodified lines
40github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=41github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=42github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=43github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=44github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=44github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=45github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=46github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=47github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=48github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=49github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=50github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
19 unmodified lines
70github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=71github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=72github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=73github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=73go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=74go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=75golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=76golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=74go.mongodb.org/mongo-driver v1.17.7 h1:a9w+U3Vt67eYzcfq3k/OAv284/uUUkL0uP75VE5rCOU=75go.mongodb.org/mongo-driver v1.17.7/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=76go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=77go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=78golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=79golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=80golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=81golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=82golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=83golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
15 unmodified lines