Skip to content
Myr

Fix #216: Enable to call binding multiple times in some formats (#1341)

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

* Add interface to read body bytes in binding * Add BindingBody implementation for some binding * Fix to use `BindBodyBytesKey` for key * Revert "Fix to use `BindBodyBytesKey` for key" This reverts commit 2c82901ceab6ae53730a3cfcd9839bee11a08f13. * Use private-like key for body bytes * Add tests for BindingBody & ShouldBindBodyWith * Add note for README * Remove redundant space between sentences

authored by JINNOUCHI Yasushi · committed by Bo-Yi Wu · parent 6e09ef0 · Browse files · 9 files+279 added−10 removed
This commit

State

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

Diff stats

9 files+279 added−10 removed

  • other:+279 added−10 removed

9 files+279 added−10 removed

added:binding/binding_body_test.go+67 added
1package binding23import (4 "bytes"5 "io/ioutil"6 "testing"78 "github.com/gin-gonic/gin/binding/example"9 "github.com/golang/protobuf/proto"10 "github.com/stretchr/testify/assert"11 "github.com/ugorji/go/codec"12)1314func TestBindingBody(t *testing.T) {15 for _, tt := range []struct {16 name string17 binding BindingBody18 body string19 want string20 }{21 {22 name: "JSON bidning",23 binding: JSON,24 body: `{"foo":"FOO"}`,25 },26 {27 name: "XML bidning",28 binding: XML,29 body: `<?xml version="1.0" encoding="UTF-8"?>30<root>31 <foo>FOO</foo>32</root>`,33 },34 {35 name: "MsgPack binding",36 binding: MsgPack,37 body: msgPackBody(t),38 },39 } {40 t.Logf("testing: %s", tt.name)41 req := requestWithBody("POST", "/", tt.body)42 form := FooStruct{}43 body, _ := ioutil.ReadAll(req.Body)44 assert.NoError(t, tt.binding.BindBody(body, &form))45 assert.Equal(t, FooStruct{"FOO"}, form)46 }47}4849func msgPackBody(t *testing.T) string {50 test := FooStruct{"FOO"}51 h := new(codec.MsgpackHandle)52 buf := bytes.NewBuffer(nil)53 assert.NoError(t, codec.NewEncoder(buf, h).Encode(test))54 return buf.String()55}5657func TestBindingBodyProto(t *testing.T) {58 test := example.Test{59 Label: proto.String("FOO"),60 }61 data, _ := proto.Marshal(&test)62 req := requestWithBody("POST", "/", string(data))63 form := example.Test{}64 body, _ := ioutil.ReadAll(req.Body)65 assert.NoError(t, ProtoBuf.BindBody(body, &form))66 assert.Equal(t, test, form)67}
modified:binding/binding.go+7 added
27 unmodified lines
28 Name() string29 Bind(*http.Request, interface{}) error30}3132// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,33// but it reads the body from supplied bytes instead of req.Body.34type BindingBody interface {35 Binding36 BindBody([]byte, interface{}) error37}3839// StructValidator is the minimal interface which needs to be implemented in40// order for it to be used as the validator engine for ensuring the correctness41// of the reqest. Gin provides a default implementation for this using42// https://github.com/go-playground/validator/tree/v8.18.2.
58 unmodified lines
modified:binding/json.go+11 added-1 removed
3 unmodified lines
45package binding67import (8 "bytes"9 "io"10 "net/http"1112 "github.com/gin-gonic/gin/json"13)
9 unmodified lines
23 return "json"24}2526func (jsonBinding) Bind(req *http.Request, obj interface{}) error {27 return decodeJSON(req.Body, obj)28}2930func (jsonBinding) BindBody(body []byte, obj interface{}) error {31 return decodeJSON(bytes.NewReader(body), obj)32}3334func decodeJSON(r io.Reader, obj interface{}) error {25 decoder := json.NewDecoder(req.Body)35 decoder := json.NewDecoder(r)36 if EnableDecoderUseNumber {37 decoder.UseNumber()38 }39 if err := decoder.Decode(obj); err != nil {
4 unmodified lines
modified:binding/msgpack.go+12 added-1 removed
3 unmodified lines
45package binding67import (8 "bytes"9 "io"10 "net/http"1112 "github.com/ugorji/go/codec"13)
4 unmodified lines
18 return "msgpack"19}2021func (msgpackBinding) Bind(req *http.Request, obj interface{}) error {22 return decodeMsgPack(req.Body, obj)23}2425func (msgpackBinding) BindBody(body []byte, obj interface{}) error {26 return decodeMsgPack(bytes.NewReader(body), obj)27}2829func decodeMsgPack(r io.Reader, obj interface{}) error {30 cdc := new(codec.MsgpackHandle)20 if err := codec.NewDecoder(req.Body, new(codec.MsgpackHandle)).Decode(&obj); err != nil {31 if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {32 return err33 }34 return validate(obj)35}
modified:binding/protobuf.go+8 added-7 removed
15 unmodified lines
16func (protobufBinding) Name() string {17 return "protobuf"18}1920func (protobufBinding) Bind(req *http.Request, obj interface{}) error {2120func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {21 buf, err := ioutil.ReadAll(req.Body)22 if err != nil {23 return err24 }25 return b.BindBody(buf, obj)26}2728func (protobufBinding) BindBody(body []byte, obj interface{}) error {27 if err = proto.Unmarshal(buf, obj.(proto.Message)); err != nil {29 if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil {30 return err31 }3031 //Here it's same to return validate(obj), but util now we cann't add `binding:""` to the struct32 //which automatically generate by gen-proto32 // Here it's same to return validate(obj), but util now we cann't add33 // `binding:""` to the struct which automatically generate by gen-proto34 return nil34 //return validate(obj)35 // return validate(obj)36}
modified:binding/xml.go+10 added-1 removed
3 unmodified lines
45package binding67import (8 "bytes"9 "encoding/xml"10 "io"11 "net/http"12)1314type xmlBinding struct{}
2 unmodified lines
17 return "xml"18}1920func (xmlBinding) Bind(req *http.Request, obj interface{}) error {21 return decodeXML(req.Body, obj)22}2324func (xmlBinding) BindBody(body []byte, obj interface{}) error {25 return decodeXML(bytes.NewReader(body), obj)26}27func decodeXML(r io.Reader, obj interface{}) error {19 decoder := xml.NewDecoder(req.Body)28 decoder := xml.NewDecoder(r)29 if err := decoder.Decode(obj); err != nil {30 return err31 }32 return validate(obj)
1 unmodified line
modified:context_test.go+80 added
16 unmodified lines
17 "testing"18 "time"1920 "github.com/gin-contrib/sse"21 "github.com/gin-gonic/gin/binding"22 "github.com/stretchr/testify/assert"23 "golang.org/x/net/context"24)25
1308 unmodified lines
1334 assert.Empty(t, obj.Foo)1335 assert.False(t, c.IsAborted())1336}13371338func TestContextShouldBindBodyWith(t *testing.T) {1339 type typeA struct {1340 Foo string `json:"foo" xml:"foo" binding:"required"`1341 }1342 type typeB struct {1343 Bar string `json:"bar" xml:"bar" binding:"required"`1344 }1345 for _, tt := range []struct {1346 name string1347 bindingA, bindingB binding.BindingBody1348 bodyA, bodyB string1349 }{1350 {1351 name: "JSON & JSON",1352 bindingA: binding.JSON,1353 bindingB: binding.JSON,1354 bodyA: `{"foo":"FOO"}`,1355 bodyB: `{"bar":"BAR"}`,1356 },1357 {1358 name: "JSON & XML",1359 bindingA: binding.JSON,1360 bindingB: binding.XML,1361 bodyA: `{"foo":"FOO"}`,1362 bodyB: `<?xml version="1.0" encoding="UTF-8"?>1363<root>1364 <bar>BAR</bar>1365</root>`,1366 },1367 {1368 name: "XML & XML",1369 bindingA: binding.XML,1370 bindingB: binding.XML,1371 bodyA: `<?xml version="1.0" encoding="UTF-8"?>1372<root>1373 <foo>FOO</foo>1374</root>`,1375 bodyB: `<?xml version="1.0" encoding="UTF-8"?>1376<root>1377 <bar>BAR</bar>1378</root>`,1379 },1380 } {1381 t.Logf("testing: %s", tt.name)1382 // bodyA to typeA and typeB1383 {1384 w := httptest.NewRecorder()1385 c, _ := CreateTestContext(w)1386 c.Request, _ = http.NewRequest(1387 "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),1388 )1389 // When it binds to typeA and typeB, it finds the body is1390 // not typeB but typeA.1391 objA := typeA{}1392 assert.NoError(t, c.ShouldBindBodyWith(&objA, tt.bindingA))1393 assert.Equal(t, typeA{"FOO"}, objA)1394 objB := typeB{}1395 assert.Error(t, c.ShouldBindBodyWith(&objB, tt.bindingB))1396 assert.NotEqual(t, typeB{"BAR"}, objB)1397 }1398 // bodyB to typeA and typeB1399 {1400 // When it binds to typeA and typeB, it finds the body is1401 // not typeA but typeB.1402 w := httptest.NewRecorder()1403 c, _ := CreateTestContext(w)1404 c.Request, _ = http.NewRequest(1405 "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),1406 )1407 objA := typeA{}1408 assert.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))1409 assert.NotEqual(t, typeA{"FOO"}, objA)1410 objB := typeB{}1411 assert.NoError(t, c.ShouldBindBodyWith(&objB, tt.bindingB))1412 assert.Equal(t, typeB{"BAR"}, objB)1413 }1414 }1415}14161417func TestContextGolangContext(t *testing.T) {1418 c, _ := CreateTestContext(httptest.NewRecorder())1419 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1420 assert.NoError(t, c.Err())
53 unmodified lines
modified:context.go+25 added
29 unmodified lines
30 MIMEXML2 = binding.MIMEXML231 MIMEPlain = binding.MIMEPlain32 MIMEPOSTForm = binding.MIMEPOSTForm33 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm34 BodyBytesKey = "_gin-gonic/gin/bodybyteskey"35)3637const abortIndex int8 = math.MaxInt8 / 238
469 unmodified lines
508func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {509 return b.Bind(c.Request, obj)510}511512// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request513// body into the context, and reuse when it is called again.514//515// NOTE: This method reads the body before binding. So you should use516// ShouldBindWith for better performance if you need to call only once.517func (c *Context) ShouldBindBodyWith(518 obj interface{}, bb binding.BindingBody,519) (err error) {520 var body []byte521 if cb, ok := c.Get(BodyBytesKey); ok {522 if cbb, ok := cb.([]byte); ok {523 body = cbb524 }525 }526 if body == nil {527 body, err = ioutil.ReadAll(c.Request.Body)528 if err != nil {529 return err530 }531 c.Set(BodyBytesKey, body)532 }533 return bb.BindBody(body, obj)534}535536// ClientIP implements a best effort algorithm to return the real client IP, it parses537// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.538// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.539func (c *Context) ClientIP() string {
315 unmodified lines
modified:README.md+59 added
50 unmodified lines
51 - [Run multiple service using Gin](#run-multiple-service-using-gin)52 - [Graceful restart or stop](#graceful-restart-or-stop)53 - [Build a single binary with templates](#build-a-single-binary-with-templates)54 - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)55 - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)56- [Testing](#testing)57- [Users](#users--)5859## Quick start
1494 unmodified lines
1554```15551556In a word, only support nested custom struct which have no `form` now.15571558### Try to bind body into different structs15591560The normal methods for binding request body consumes `c.Request.Body` and they1561cannot be called multiple times.15621563```go1564type formA struct {1565 Foo string `json:"foo" xml:"foo" binding:"required"`1566}15671568type formB struct {1569 Bar string `json:"bar" xml:"bar" binding:"required"`1570}15711572func SomeHandler(c *gin.Context) {1573 objA := formA{}1574 objB := formB{}1575 // This c.ShouldBind consumes c.Request.Body and it cannot be reused.1576 if errA := c.ShouldBind(&objA); errA == nil {1577 c.String(http.StatusOK, `the body should be formA`)1578 // Always an error is occurred by this because c.Request.Body is EOF now.1579 } else if errB := c.ShouldBind(&objB); errB == nil {1580 c.String(http.StatusOK, `the body should be formB`)1581 } else {1582 ...1583 }1584}1585```15861587For this, you can use `c.ShouldBindBodyWith`.15881589```go1590func SomeHandler(c *gin.Context) {1591 objA := formA{}1592 objB := formB{}1593 // This reads c.Request.Body and stores the result into the context.1594 if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {1595 c.String(http.StatusOK, `the body should be formA`)1596 // At this time, it reuses body stored in the context.1597 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1598 c.String(http.StatusOK, `the body should be formB JSON`)1599 // And it can accepts other formats1600 } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {1601 c.String(http.StatusOK, `the body should be formB XML`)1602 } else {1603 ...1604 }1605}1606```16071608* `c.ShouldBindBodyWith` stores body into the context before binding. This has1609a slight impact to performance, so you should not use this method if you are1610enough to call binding at once.1611* This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1612`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1613can be called by `c.ShouldBind()` multiple times without any damage to1614performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).16151616## Testing16171618The `net/http/httptest` package is preferable way for HTTP testing.1619
48 unmodified lines