Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add bson protocol #4145

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions binding/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const (
MIMEYAML = "application/x-yaml"
MIMEYAML2 = "application/yaml"
MIMETOML = "application/toml"
MIMEBSON = "application/bson"
)

// Binding describes the interface which needs to be implemented for binding the
Expand Down Expand Up @@ -86,6 +87,7 @@ var (
Header Binding = headerBinding{}
Plain BindingBody = plainBinding{}
TOML BindingBody = tomlBinding{}
BSON BindingBody = bsonBinding{}
)

// Default returns the appropriate Binding instance based on the HTTP method
Expand All @@ -110,6 +112,8 @@ func Default(method, contentType string) Binding {
return TOML
case MIMEMultipartPOSTForm:
return FormMultipart
case MIMEBSON:
return BSON
default: // case MIMEPOSTForm:
return Form
}
Expand Down
14 changes: 14 additions & 0 deletions binding/binding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"google.golang.org/protobuf/proto"
)

Expand Down Expand Up @@ -170,6 +171,9 @@ func TestBindingDefault(t *testing.T) {

assert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))
assert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))

assert.Equal(t, BSON, Default(http.MethodPost, MIMEBSON))
assert.Equal(t, BSON, Default(http.MethodPut, MIMEBSON))
}

func TestBindingJSONNilBody(t *testing.T) {
Expand Down Expand Up @@ -729,6 +733,16 @@ func TestBindingProtoBufFail(t *testing.T) {
string(data), string(data[1:]))
}

func TestBindingBSON(t *testing.T) {
var obj FooStruct
obj.Foo = "bar"
data, _ := bson.Marshal(&obj)
testBodyBinding(t,
BSON, "bson",
"/", "/",
string(data), string(data[1:]))
}

func TestValidationFails(t *testing.T) {
var obj FooStruct
req := requestWithBody(http.MethodPost, "/", `{"bar": "foo"}`)
Expand Down
30 changes: 30 additions & 0 deletions binding/bson.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Copyright 2025 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package binding

import (
"io"
"net/http"

"go.mongodb.org/mongo-driver/bson"
)

type bsonBinding struct{}

func (bsonBinding) Name() string {
return "bson"
}

func (b bsonBinding) Bind(req *http.Request, obj any) error {
buf, err := io.ReadAll(req.Body)
if err != nil {
return err
}
return b.BindBody(buf, obj)
}

func (bsonBinding) BindBody(body []byte, obj any) error {
return bson.Unmarshal(body, obj)
}
11 changes: 11 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
MIMEYAML = binding.MIMEYAML
MIMEYAML2 = binding.MIMEYAML2
MIMETOML = binding.MIMETOML
MIMEBSON = binding.MIMEBSON

Check failure on line 40 in context.go

View workflow job for this annotation

GitHub Actions / ubuntu-latest @ Go 1.22 -tags nomsgpack

undefined: binding.MIMEBSON

Check failure on line 40 in context.go

View workflow job for this annotation

GitHub Actions / ubuntu-latest @ Go 1.23 -tags nomsgpack

undefined: binding.MIMEBSON

Check failure on line 40 in context.go

View workflow job for this annotation

GitHub Actions / macos-latest @ Go 1.22 -tags nomsgpack

undefined: binding.MIMEBSON
)

// BodyBytesKey indicates a default body bytes key.
Expand Down Expand Up @@ -1131,6 +1132,11 @@
c.Render(code, render.ProtoBuf{Data: obj})
}

// BSON serializes the given struct as BSON into the response body.
func (c *Context) BSON(code int, obj any) {
c.Render(code, render.BSON{Data: obj})
}

// String writes the given string into the response body.
func (c *Context) String(code int, format string, values ...any) {
c.Render(code, render.String{Format: format, Data: values})
Expand Down Expand Up @@ -1237,6 +1243,7 @@
YAMLData any
Data any
TOMLData any
BSONData any
}

// Negotiate calls different Render according to acceptable Accept format.
Expand All @@ -1262,6 +1269,10 @@
data := chooseData(config.TOMLData, config.Data)
c.TOML(code, data)

case binding.MIMEBSON:

Check failure on line 1272 in context.go

View workflow job for this annotation

GitHub Actions / ubuntu-latest @ Go 1.22 -tags nomsgpack

undefined: binding.MIMEBSON

Check failure on line 1272 in context.go

View workflow job for this annotation

GitHub Actions / ubuntu-latest @ Go 1.23 -tags nomsgpack

undefined: binding.MIMEBSON

Check failure on line 1272 in context.go

View workflow job for this annotation

GitHub Actions / macos-latest @ Go 1.22 -tags nomsgpack

undefined: binding.MIMEBSON
data := chooseData(config.BSONData, config.Data)
c.BSON(code, data)

default:
c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck
}
Expand Down
18 changes: 18 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"google.golang.org/protobuf/proto"
)

Expand Down Expand Up @@ -1499,6 +1500,23 @@ func TestContextNegotiationWithHTML(t *testing.T) {
assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
}

func TestContextNegotiationWithBSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest(http.MethodPost, "", nil)

c.Negotiate(http.StatusOK, Negotiate{
Offered: []string{MIMEBSON, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},
Data: H{"foo": "bar"},
})

bData, _ := bson.Marshal(H{"foo": "bar"})

assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, string(bData), w.Body.String())
assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))
}

func TestContextNegotiationNotSupport(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
go.mongodb.org/mongo-driver v1.17.2 // indirect
go.uber.org/mock v0.4.0 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
golang.org/x/crypto v0.31.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
go.mongodb.org/mongo-driver v1.17.2 h1:gvZyk8352qSfzyZ2UMWcpDpMSGEr1eqE4T793SqyhzM=
go.mongodb.org/mongo-driver v1.17.2/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU=
Expand Down
36 changes: 36 additions & 0 deletions render/bson.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2018 Gin Core Team. All rights reserved.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Copyright 2025 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package render

import (
"net/http"

"go.mongodb.org/mongo-driver/bson"
)

// BSON contains the given interface object.
type BSON struct {
Data any
}

var bsonContentType = []string{"application/bson"}

// Render (BSON) marshals the given interface object and writes data with custom ContentType.
func (r BSON) Render(w http.ResponseWriter) error {
r.WriteContentType(w)

bytes, err := bson.Marshal(&r.Data)
if err != nil {
return err
}

_, err = w.Write(bytes)
return err
}

// WriteContentType (BSONBuf) writes BSONBuf ContentType.
func (r BSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, bsonContentType)
}
23 changes: 23 additions & 0 deletions render/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"google.golang.org/protobuf/proto"
)

Expand Down Expand Up @@ -352,6 +353,28 @@ func TestRenderProtoBufFail(t *testing.T) {
require.Error(t, err)
}

func TestRenderBSON(t *testing.T) {
w := httptest.NewRecorder()
type mystruct struct {
Label string
Reps []int64
}
var data mystruct = mystruct{
Label: "test",
Reps: []int64{int64(1), int64(2)}}

(BSON{data}).WriteContentType(w)
bsonData, err := bson.Marshal(data)
require.NoError(t, err)
assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))

err = (BSON{data}).Render(w)

require.NoError(t, err)
assert.Equal(t, string(bsonData), w.Body.String())
assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))
}

func TestRenderXML(t *testing.T) {
w := httptest.NewRecorder()
data := xmlmap{
Expand Down
Loading