[GIN-001] - Add TOML bining for gin (#3081)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Valentine Oragbakosi · committed by GitHub · parent aa60021 · Browse files · 12 files·+157 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: GitstartHQ <gitstart@users.noreply.github.com>
Diff stats
12 files+157 added−3 removed
- other:+157 added−3 removed
Provenance
- Commit
ed03102- Tree
90d5435- Author
Valentine Oragbakosi <valentine13400@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
aa60021
12 files changed+157 added−3 removed
modified:binding/binding_nomsgpack.go+4 added
18 unmodified lines19 MIMEPOSTForm = "application/x-www-form-urlencoded"20 MIMEMultipartPOSTForm = "multipart/form-data"21 MIMEPROTOBUF = "application/x-protobuf"22 MIMEYAML = "application/x-yaml"23+ MIMETOML = "application/toml"24 )25 26 // Binding describes the interface which needs to be implemented for binding the27 // data present in the request such as JSON request body, query parameters or51 unmodified lines79 ProtoBuf = protobufBinding{}80 YAML = yamlBinding{}81 Uri = uriBinding{}82 Header = headerBinding{}83+ TOML = tomlBinding{}84 )85 86 // Default returns the appropriate Binding instance based on the HTTP method87 // and the content type.12 unmodified lines100 case MIMEYAML:101 return YAML102 case MIMEMultipartPOSTForm:103 return FormMultipart104+ case MIMETOML:105+ return TOML106 default: // case MIMEPOSTForm:107 return Form108 }109 }7 unmodified linesmodified:binding/binding_test.go+17 added
163 unmodified lines164 assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))165 166 assert.Equal(t, YAML, Default("POST", MIMEYAML))167 assert.Equal(t, YAML, Default("PUT", MIMEYAML))168+169+ assert.Equal(t, TOML, Default("POST", MIMETOML))170+ assert.Equal(t, TOML, Default("PUT", MIMETOML))171 }172 173 func TestBindingJSONNilBody(t *testing.T) {174 var obj FooStruct281 unmodified lines456 "/", "/",457 "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")458 }459 460+func TestBindingTOML(t *testing.T) {461+ testBodyBinding(t,462+ TOML, "toml",463+ "/", "/",464+ `foo="bar"`, `bar="foo"`)465+}466+467+func TestBindingTOMLFail(t *testing.T) {468+ testBodyBindingFail(t,469+ TOML, "toml",470+ "/", "/",471+ `foo=\n"bar"`, `bar="foo"`)472+}473+474 func TestBindingYAML(t *testing.T) {475 testBodyBinding(t,476 YAML, "yaml",477 "/", "/",899 unmodified linesmodified:binding/binding.go+4 added
20 unmodified lines21 MIMEPROTOBUF = "application/x-protobuf"22 MIMEMSGPACK = "application/x-msgpack"23 MIMEMSGPACK2 = "application/msgpack"24 MIMEYAML = "application/x-yaml"25+ MIMETOML = "application/toml"26 )27 28 // Binding describes the interface which needs to be implemented for binding the29 // data present in the request such as JSON request body, query parameters or53 unmodified lines83 MsgPack = msgpackBinding{}84 YAML = yamlBinding{}85 Uri = uriBinding{}86 Header = headerBinding{}87+ TOML = tomlBinding{}88 )89 90 // Default returns the appropriate Binding instance based on the HTTP method91 // and the content type.12 unmodified lines104 case MIMEMSGPACK, MIMEMSGPACK2:105 return MsgPack106 case MIMEYAML:107 return YAML108+ case MIMETOML:109+ return TOML110 case MIMEMultipartPOSTForm:111 return FormMultipart112 default: // case MIMEPOSTForm:113 return Form9 unmodified linesadded:binding/toml_test.go+22 added
1+// Copyright 2022 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+ "testing"9+10+ "github.com/stretchr/testify/assert"11+ "github.com/stretchr/testify/require"12+)13+14+func TestTOMLBindingBindBody(t *testing.T) {15+ var s struct {16+ Foo string `toml:"foo"`17+ }18+ tomlBody := `foo="FOO"`19+ err := tomlBinding{}.BindBody([]byte(tomlBody), &s)20+ require.NoError(t, err)21+ assert.Equal(t, "FOO", s.Foo)22+}added:binding/toml.go+31 added
1+package binding2+3+import (4+ "bytes"5+ "io"6+ "net/http"7+8+ "github.com/pelletier/go-toml/v2"9+)10+11+type tomlBinding struct{}12+13+func (tomlBinding) Name() string {14+ return "toml"15+}16+17+func decodeToml(r io.Reader, obj any) error {18+ decoder := toml.NewDecoder(r)19+ if err := decoder.Decode(obj); err != nil {20+ return err21+ }22+ return decoder.Decode(obj)23+}24+25+func (tomlBinding) Bind(req *http.Request, obj any) error {26+ return decodeToml(req.Body, obj)27+}28+29+func (tomlBinding) BindBody(body []byte, obj any) error {30+ return decodeToml(bytes.NewReader(body), obj)31+}modified:render/render.go+1 added
28 unmodified lines29 _ Render = YAML{}30 _ Render = Reader{}31 _ Render = AsciiJSON{}32 _ Render = ProtoBuf{}33+ _ Render = TOML{}34 )35 36 func writeContentType(w http.ResponseWriter, value []string) {37 header := w.Header()4 unmodified linesadded:render/toml.go+32 added
1+package render2+3+import (4+ "net/http"5+6+ "github.com/pelletier/go-toml/v2"7+)8+9+// TOML contains the given interface object.10+type TOML struct {11+ Data any12+}13+14+var TOMLContentType = []string{"application/toml; charset=utf-8"}15+16+// Render (TOML) marshals the given interface object and writes data with custom ContentType.17+func (r TOML) Render(w http.ResponseWriter) error {18+ r.WriteContentType(w)19+20+ bytes, err := toml.Marshal(r.Data)21+ if err != nil {22+ return err23+ }24+25+ _, err = w.Write(bytes)26+ return err27+}28+29+// WriteContentType (TOML) writes TOML ContentType for response.30+func (r TOML) WriteContentType(w http.ResponseWriter) {31+ writeContentType(w, TOMLContentType)32+}modified:context_test.go+17 added
1771 unmodified lines1772 assert.Equal(t, "bar", obj.Foo)1773 assert.Equal(t, 0, w.Body.Len())1774 }1775 1776+func TestContextShouldBindWithTOML(t *testing.T) {1777+ w := httptest.NewRecorder()1778+ c, _ := CreateTestContext(w)1779+1780+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))1781+ c.Request.Header.Add("Content-Type", MIMETOML) // set fake content-type1782+1783+ var obj struct {1784+ Foo string `toml:"foo"`1785+ Bar string `toml:"bar"`1786+ }1787+ assert.NoError(t, c.ShouldBindTOML(&obj))1788+ assert.Equal(t, "foo", obj.Bar)1789+ assert.Equal(t, "bar", obj.Foo)1790+ assert.Equal(t, 0, w.Body.Len())1791+}1792+1793 func TestContextBadAutoShouldBind(t *testing.T) {1794 w := httptest.NewRecorder()1795 c, _ := CreateTestContext(w)1796 409 unmodified linesmodified:context.go+21 added
32 unmodified lines33 MIMEPlain = binding.MIMEPlain34 MIMEPOSTForm = binding.MIMEPOSTForm35 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm36 MIMEYAML = binding.MIMEYAML37+ MIMETOML = binding.MIMETOML38 )39 40 // BodyBytesKey indicates a default body bytes key.41 const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"594 unmodified lines636 func (c *Context) BindYAML(obj any) error {637 return c.MustBindWith(obj, binding.YAML)638 }639 640+// BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML).641+func (c *Context) BindTOML(obj interface{}) error {642+ return c.MustBindWith(obj, binding.TOML)643+}644+645 // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).646 func (c *Context) BindHeader(obj any) error {647 return c.MustBindWith(obj, binding.Header)648 }50 unmodified lines699 func (c *Context) ShouldBindYAML(obj any) error {700 return c.ShouldBindWith(obj, binding.YAML)701 }702 703+// ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML).704+func (c *Context) ShouldBindTOML(obj interface{}) error {705+ return c.ShouldBindWith(obj, binding.TOML)706+}707+708 // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).709 func (c *Context) ShouldBindHeader(obj any) error {710 return c.ShouldBindWith(obj, binding.Header)711 }263 unmodified lines975 func (c *Context) YAML(code int, obj any) {976 c.Render(code, render.YAML{Data: obj})977 }978 979+// TOML serializes the given struct as TOML into the response body.980+func (c *Context) TOML(code int, obj interface{}) {981+ c.Render(code, render.TOML{Data: obj})982+}983+984 // ProtoBuf serializes the given struct as ProtoBuf into the response body.985 func (c *Context) ProtoBuf(code int, obj any) {986 c.Render(code, render.ProtoBuf{Data: obj})987 }96 unmodified lines1084 JSONData any1085 XMLData any1086 YAMLData any1087 Data any1088+ TOMLData any1089 }1090 1091 // Negotiate calls different Render according to acceptable Accept format.1092 func (c *Context) Negotiate(code int, config Negotiate) {13 unmodified lines1106 case binding.MIMEYAML:1107 data := chooseData(config.YAMLData, config.Data)1108 c.YAML(code, data)1109 1110+ case binding.MIMETOML:1111+ data := chooseData(config.TOMLData, config.Data)1112+ c.TOML(code, data)1113+1114 default:1115 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck1116 }1117 }85 unmodified linesmodified:go.mod+1 added
6 unmodified lines7 github.com/go-playground/validator/v10 v10.10.08 github.com/goccy/go-json v0.9.79 github.com/json-iterator/go v1.1.1210 github.com/mattn/go-isatty v0.0.1411+ github.com/pelletier/go-toml/v2 v2.0.0-beta.612 github.com/stretchr/testify v1.7.113 github.com/ugorji/go/codec v1.2.714 golang.org/x/net v0.0.0-20210226172049-e18ecbb0511015 google.golang.org/protobuf v1.28.016 unmodified linesmodified:go.sum+4 added
34 unmodified lines35 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=36 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=37 github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=38 github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=39+github.com/pelletier/go-toml/v2 v2.0.0-beta.6 h1:JFNqj2afbbhCqTiyN16D7Tudc/aaDzE2FBDk+VlBQnE=40+github.com/pelletier/go-toml/v2 v2.0.0-beta.6/go.mod h1:ke6xncR3W76Ba8xnVxkrZG0js6Rd2BsQEAYrfgJ6eQA=41 github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=42 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=43 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=44 github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=2 unmodified lines47 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=48 github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=49 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=50 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=51+github.com/stretchr/testify v1.7.1-0.20210427113832-6241f9ab9942/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=52 github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=53 github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=54+github.com/ugorji/go v1.2.7 h1:qYhyWUUd6WbiM+C6JZAUkIJt/1WrjzNHY9+KCIjVqTo=55 github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=56 github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=57 github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=58 golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 h1:/UOmuWzQfxxo9UtlXMwuQU8CMgg1eZXqTRwkSQJWKOI=28 unmodified linesmodified:README.md+3 added-3 removed
656 unmodified lines657 ```658 659 ### Model binding and validation660 661-To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML and standard form values (foo=bar&boo=baz).661+To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz).662 663 Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags).664 665 Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.666 667 Also, Gin provides two sets of methods for binding:668 - **Type** - Must bind669- - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`669+ - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`670 - **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method.671 - **Type** - Should bind672- - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`672+ - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,673 - **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately.674 675 When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use `MustBindWith` or `ShouldBindWith`.676 1651 unmodified lines