Skip to content
Myr

[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

12 files+157 added−3 removed

modified:binding/binding_nomsgpack.go+4 added
18 unmodified lines
19 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)2526// Binding describes the interface which needs to be implemented for binding the27// data present in the request such as JSON request body, query parameters or
51 unmodified lines
79 ProtoBuf = protobufBinding{}80 YAML = yamlBinding{}81 Uri = uriBinding{}82 Header = headerBinding{}83 TOML = tomlBinding{}84)8586// Default returns the appropriate Binding instance based on the HTTP method87// and the content type.
12 unmodified lines
100 case MIMEYAML:101 return YAML102 case MIMEMultipartPOSTForm:103 return FormMultipart104 case MIMETOML:105 return TOML106 default: // case MIMEPOSTForm:107 return Form108 }109}
7 unmodified lines
modified:binding/binding_test.go+17 added
163 unmodified lines
164 assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))165166 assert.Equal(t, YAML, Default("POST", MIMEYAML))167 assert.Equal(t, YAML, Default("PUT", MIMEYAML))168169 assert.Equal(t, TOML, Default("POST", MIMETOML))170 assert.Equal(t, TOML, Default("PUT", MIMETOML))171}172173func TestBindingJSONNilBody(t *testing.T) {174 var obj FooStruct
281 unmodified lines
456 "/", "/",457 "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")458}459460func TestBindingTOML(t *testing.T) {461 testBodyBinding(t,462 TOML, "toml",463 "/", "/",464 `foo="bar"`, `bar="foo"`)465}466467func TestBindingTOMLFail(t *testing.T) {468 testBodyBindingFail(t,469 TOML, "toml",470 "/", "/",471 `foo=\n"bar"`, `bar="foo"`)472}473474func TestBindingYAML(t *testing.T) {475 testBodyBinding(t,476 YAML, "yaml",477 "/", "/",
899 unmodified lines
modified:binding/binding.go+4 added
20 unmodified lines
21 MIMEPROTOBUF = "application/x-protobuf"22 MIMEMSGPACK = "application/x-msgpack"23 MIMEMSGPACK2 = "application/msgpack"24 MIMEYAML = "application/x-yaml"25 MIMETOML = "application/toml"26)2728// Binding describes the interface which needs to be implemented for binding the29// data present in the request such as JSON request body, query parameters or
53 unmodified lines
83 MsgPack = msgpackBinding{}84 YAML = yamlBinding{}85 Uri = uriBinding{}86 Header = headerBinding{}87 TOML = tomlBinding{}88)8990// Default returns the appropriate Binding instance based on the HTTP method91// and the content type.
12 unmodified lines
104 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 Form
9 unmodified lines
added: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.45package binding67import (8 "testing"910 "github.com/stretchr/testify/assert"11 "github.com/stretchr/testify/require"12)1314func 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
1package binding23import (4 "bytes"5 "io"6 "net/http"78 "github.com/pelletier/go-toml/v2"9)1011type tomlBinding struct{}1213func (tomlBinding) Name() string {14 return "toml"15}1617func 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}2425func (tomlBinding) Bind(req *http.Request, obj any) error {26 return decodeToml(req.Body, obj)27}2829func (tomlBinding) BindBody(body []byte, obj any) error {30 return decodeToml(bytes.NewReader(body), obj)31}
modified:render/render.go+1 added
28 unmodified lines
29 _ Render = YAML{}30 _ Render = Reader{}31 _ Render = AsciiJSON{}32 _ Render = ProtoBuf{}33 _ Render = TOML{}34)3536func writeContentType(w http.ResponseWriter, value []string) {37 header := w.Header()
4 unmodified lines
added:render/toml.go+32 added
1package render23import (4 "net/http"56 "github.com/pelletier/go-toml/v2"7)89// TOML contains the given interface object.10type TOML struct {11 Data any12}1314var TOMLContentType = []string{"application/toml; charset=utf-8"}1516// Render (TOML) marshals the given interface object and writes data with custom ContentType.17func (r TOML) Render(w http.ResponseWriter) error {18 r.WriteContentType(w)1920 bytes, err := toml.Marshal(r.Data)21 if err != nil {22 return err23 }2425 _, err = w.Write(bytes)26 return err27}2829// WriteContentType (TOML) writes TOML ContentType for response.30func (r TOML) WriteContentType(w http.ResponseWriter) {31 writeContentType(w, TOMLContentType)32}
modified:context_test.go+17 added
1771 unmodified lines
1772 assert.Equal(t, "bar", obj.Foo)1773 assert.Equal(t, 0, w.Body.Len())1774}17751776func TestContextShouldBindWithTOML(t *testing.T) {1777 w := httptest.NewRecorder()1778 c, _ := CreateTestContext(w)17791780 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))1781 c.Request.Header.Add("Content-Type", MIMETOML) // set fake content-type17821783 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}17921793func TestContextBadAutoShouldBind(t *testing.T) {1794 w := httptest.NewRecorder()1795 c, _ := CreateTestContext(w)1796
409 unmodified lines
modified:context.go+21 added
32 unmodified lines
33 MIMEPlain = binding.MIMEPlain34 MIMEPOSTForm = binding.MIMEPOSTForm35 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm36 MIMEYAML = binding.MIMEYAML37 MIMETOML = binding.MIMETOML38)3940// BodyBytesKey indicates a default body bytes key.41const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
594 unmodified lines
636func (c *Context) BindYAML(obj any) error {637 return c.MustBindWith(obj, binding.YAML)638}639640// BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML).641func (c *Context) BindTOML(obj interface{}) error {642 return c.MustBindWith(obj, binding.TOML)643}644645// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).646func (c *Context) BindHeader(obj any) error {647 return c.MustBindWith(obj, binding.Header)648}
50 unmodified lines
699func (c *Context) ShouldBindYAML(obj any) error {700 return c.ShouldBindWith(obj, binding.YAML)701}702703// ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML).704func (c *Context) ShouldBindTOML(obj interface{}) error {705 return c.ShouldBindWith(obj, binding.TOML)706}707708// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).709func (c *Context) ShouldBindHeader(obj any) error {710 return c.ShouldBindWith(obj, binding.Header)711}
263 unmodified lines
975func (c *Context) YAML(code int, obj any) {976 c.Render(code, render.YAML{Data: obj})977}978979// TOML serializes the given struct as TOML into the response body.980func (c *Context) TOML(code int, obj interface{}) {981 c.Render(code, render.TOML{Data: obj})982}983984// ProtoBuf serializes the given struct as ProtoBuf into the response body.985func (c *Context) ProtoBuf(code int, obj any) {986 c.Render(code, render.ProtoBuf{Data: obj})987}
96 unmodified lines
1084 JSONData any1085 XMLData any1086 YAMLData any1087 Data any1088 TOMLData any1089}10901091// Negotiate calls different Render according to acceptable Accept format.1092func (c *Context) Negotiate(code int, config Negotiate) {
13 unmodified lines
1106 case binding.MIMEYAML:1107 data := chooseData(config.YAMLData, config.Data)1108 c.YAML(code, data)11091110 case binding.MIMETOML:1111 data := chooseData(config.TOMLData, config.Data)1112 c.TOML(code, data)11131114 default:1115 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck1116 }1117}
85 unmodified lines
modified:go.mod+1 added
6 unmodified lines
7 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.0
16 unmodified lines
modified:go.sum+4 added
34 unmodified lines
35github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=36github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=37github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=38github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=39github.com/pelletier/go-toml/v2 v2.0.0-beta.6 h1:JFNqj2afbbhCqTiyN16D7Tudc/aaDzE2FBDk+VlBQnE=40github.com/pelletier/go-toml/v2 v2.0.0-beta.6/go.mod h1:ke6xncR3W76Ba8xnVxkrZG0js6Rd2BsQEAYrfgJ6eQA=41github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=42github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=43github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=44github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
2 unmodified lines
47github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=48github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=49github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=50github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=51github.com/stretchr/testify v1.7.1-0.20210427113832-6241f9ab9942/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=52github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=53github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=54github.com/ugorji/go v1.2.7 h1:qYhyWUUd6WbiM+C6JZAUkIJt/1WrjzNHY9+KCIjVqTo=55github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=56github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=57github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=58golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 h1:/UOmuWzQfxxo9UtlXMwuQU8CMgg1eZXqTRwkSQJWKOI=
28 unmodified lines
modified:README.md+3 added-3 removed
656 unmodified lines
657```658659### Model binding and validation660661To 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).661To 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).662663Gin 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).664665Note 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"`.666667Also, 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.674675When 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