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
Provenance
- Commit
d7776de- Tree
cb4860a- Author
Laurent Caumont <40688874+laurentcau@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
e3118cc
10 files changed+162 added−11 removed
modified:binding/binding_nomsgpack.go+4 added
19 unmodified lines20 MIMEPROTOBUF = "application/x-protobuf"21 MIMEYAML = "application/x-yaml"22 MIMEYAML2 = "application/yaml"23 MIMETOML = "application/toml"24+ MIMEBSON = "application/bson"25 )26 27 // Binding describes the interface which needs to be implemented for binding the28 // data present in the request such as JSON request body, query parameters or53 unmodified lines82 Uri = uriBinding{}83 Header = headerBinding{}84 TOML = tomlBinding{}85 Plain = plainBinding{}86+ BSON BindingBody = bsonBinding{}87 )88 89 // Default returns the appropriate Binding instance based on the HTTP method90 // and the content type.14 unmodified lines105 case MIMEMultipartPOSTForm:106 return FormMultipart107 case MIMETOML:108 return TOML109+ case MIMEBSON:110+ return BSON111 default: // case MIMEPOSTForm:112 return Form113 }114 }7 unmodified linesmodified:binding/binding_test.go+16 added
19 unmodified lines20 21 "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 )27 28 type appkey struct {143 unmodified lines172 assert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML2))173 174 assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))175 assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))176+177+ assert.Equal(t, BSON, Default(http.MethodPost, MIMEBSON))178+ assert.Equal(t, BSON, Default(http.MethodPut, MIMEBSON))179 }180 181 func TestBindingJSONNilBody(t *testing.T) {182 var obj FooStruct551 unmodified lines734 "/", "/",735 string(data), string(data[1:]))736 }737 738+func 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+}749+750 func TestValidationFails(t *testing.T) {751 var obj FooStruct752 req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)753 err := JSON.Bind(req, &obj)681 unmodified linesmodified:binding/binding.go+4 added
21 unmodified lines22 MIMEMSGPACK2 = "application/msgpack"23 MIMEYAML = "application/x-yaml"24 MIMEYAML2 = "application/yaml"25 MIMETOML = "application/toml"26+ MIMEBSON = "application/bson"27 )28 29 // Binding describes the interface which needs to be implemented for binding the30 // data present in the request such as JSON request body, query parameters or55 unmodified lines86 Uri BindingUri = uriBinding{}87 Header Binding = headerBinding{}88 Plain BindingBody = plainBinding{}89 TOML BindingBody = tomlBinding{}90+ BSON BindingBody = bsonBinding{}91 )92 93 // Default returns the appropriate Binding instance based on the HTTP method94 // and the content type.16 unmodified lines111 case MIMETOML:112 return TOML113 case MIMEMultipartPOSTForm:114 return FormMultipart115+ case MIMEBSON:116+ return BSON117 default: // case MIMEPOSTForm:118 return Form119 }120 }7 unmodified linesadded: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.4+5+package binding6+7+import (8+ "io"9+ "net/http"10+11+ "go.mongodb.org/mongo-driver/bson"12+)13+14+type bsonBinding struct{}15+16+func (bsonBinding) Name() string {17+ return "bson"18+}19+20+func (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+}27+28+func (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.4+5+package render6+7+import (8+ "net/http"9+10+ "go.mongodb.org/mongo-driver/bson"11+)12+13+// BSON contains the given interface object.14+type BSON struct {15+ Data any16+}17+18+var bsonContentType = []string{"application/bson"}19+20+// Render (BSON) marshals the given interface object and writes data with custom ContentType.21+func (r BSON) Render(w http.ResponseWriter) error {22+ r.WriteContentType(w)23+24+ bytes, err := bson.Marshal(&r.Data)25+ if err == nil {26+ _, err = w.Write(bytes)27+ }28+ return err29+}30+31+// WriteContentType (BSONBuf) writes BSONBuf ContentType.32+func (r BSON) WriteContentType(w http.ResponseWriter) {33+ writeContentType(w, bsonContentType)34+}modified:render/render_test.go+26 added
17 unmodified lines18 "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 )25 26 // TODO unit tests332 unmodified lines359 err := (ProtoBuf{data}).Render(w)360 require.Error(t, err)361 }362 363+func TestRenderBSON(t *testing.T) {364+ w := httptest.NewRecorder()365+ reps := []int64{int64(1), int64(2)}366+ type mystruct struct {367+ Label string368+ Reps []int64369+ }370+371+ data := &mystruct{372+ Label: "test",373+ Reps: reps,374+ }375+376+ (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"))380+381+ err = (BSON{data}).Render(w)382+383+ require.NoError(t, err)384+ assert.Equal(t, bsonData, w.Body.Bytes())385+ assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))386+}387+388 func TestRenderXML(t *testing.T) {389 w := httptest.NewRecorder()390 data := xmlmap{391 "foo": "bar",263 unmodified linesmodified:context_test.go+18 added
30 unmodified lines31 "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 )38 39 var _ context.Context = (*Context)(nil)1661 unmodified lines1701 assert.Equal(t, string(protoData), w.Body.String())1702 assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))1703 }1704 1705+func TestContextNegotiationWithBSON(t *testing.T) {1706+ w := httptest.NewRecorder()1707+ c, _ := CreateTestContext(w)1708+ c.Request, _ = http.NewRequest(http.MethodPost, "", nil)1709+1710+ c.Negotiate(http.StatusOK, Negotiate{1711+ Offered: []string{MIMEBSON, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1712+ Data: H{"foo": "bar"},1713+ })1714+1715+ bData, _ := bson.Marshal(H{"foo": "bar"})1716+1717+ 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+}1721+1722 func TestContextNegotiationNotSupport(t *testing.T) {1723 w := httptest.NewRecorder()1724 c, _ := CreateTestContext(w)1725 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)2029 unmodified linesmodified:context.go+11 added
38 unmodified lines39 MIMEYAML = binding.MIMEYAML40 MIMEYAML2 = binding.MIMEYAML241 MIMETOML = binding.MIMETOML42 MIMEPROTOBUF = binding.MIMEPROTOBUF43+ MIMEBSON = binding.MIMEBSON44 )45 46 // BodyBytesKey indicates a default body bytes key.47 const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"1189 unmodified lines1237 func (c *Context) ProtoBuf(code int, obj any) {1238 c.Render(code, render.ProtoBuf{Data: obj})1239 }1240 1241+// BSON serializes the given struct as BSON into the response body.1242+func (c *Context) BSON(code int, obj any) {1243+ c.Render(code, render.BSON{Data: obj})1244+}1245+1246 // String writes the given string into the response body.1247 func (c *Context) String(code int, format string, values ...any) {1248 c.Render(code, render.String{Format: format, Data: values})1249 }99 unmodified lines1349 YAMLData any1350 Data any1351 TOMLData any1352 PROTOBUFData any1353+ BSONData any1354 }1355 1356 // Negotiate calls different Render according to acceptable Accept format.1357 func (c *Context) Negotiate(code int, config Negotiate) {21 unmodified lines1379 case binding.MIMEPROTOBUF:1380 data := chooseData(config.PROTOBUFData, config.Data)1381 c.ProtoBuf(code, data)1382 1383+ case binding.MIMEBSON:1384+ data := chooseData(config.BSONData, config.Data)1385+ c.BSON(code, data)1386+1387 default:1388 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck1389 }1390 }92 unmodified linesmodified:go.mod+9 added-4 removed
1 module github.com/gin-gonic/gin2 3 go 1.24.04 5+toolchain go1.24.76+7 require (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 )24 25+require gopkg.in/yaml.v3 v3.0.1 // indirect26+27 require (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 // indirect3 unmodified lines34 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 lines21 github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=22 github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=23 github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=24 github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=25-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=26-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=25+github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=26+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=27 github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE=28 github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=29 github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=30 github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=9 unmodified lines40 github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=41 github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=42 github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=43 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=44-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=44 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=45+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=46+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=47 github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=48 github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=49 github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=50 github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=19 unmodified lines70 github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=71 github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=72 github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=73 github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=73-go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=74-go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=75-golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=76-golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=74+go.mongodb.org/mongo-driver v1.17.7 h1:a9w+U3Vt67eYzcfq3k/OAv284/uUUkL0uP75VE5rCOU=75+go.mongodb.org/mongo-driver v1.17.7/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=76+go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=77+go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=78+golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=79+golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=80 golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=81 golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=82 golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=83 golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=15 unmodified lines