feat(binding): add BindPlain (#3904)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* add BindPlain * fix ci/cd error
authored by guonaihong · committed by GitHub · parent 40131af · Browse files · 6 files·+238 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+238 added−1 removed
- other:+238 added−1 removed
Provenance
- Commit
6ca8ddb- Tree
a141e18- Author
guonaihong <guonaihong@qq.com>- Committer
GitHub <noreply@github.com>- Parent
40131af
6 files changed+238 added−1 removed
modified:binding/binding_nomsgpack.go+1 added
79 unmodified lines80 YAML = yamlBinding{}81 Uri = uriBinding{}82 Header = headerBinding{}83 TOML = tomlBinding{}84+ Plain = plainBinding{}85 )86 87 // Default returns the appropriate Binding instance based on the HTTP method88 // and the content type.29 unmodified linesmodified:binding/binding_test.go+40 added
1340 unmodified lines1341 func (h hook) Read([]byte) (int, error) {1342 return 0, errors.New("error")1343 }1344 1345+type failRead struct{}1346+1347+func (f *failRead) Read(b []byte) (n int, err error) {1348+ return 0, errors.New("my fail")1349+}1350+1351+func (f *failRead) Close() error {1352+ return nil1353+}1354+1355+func TestPlainBinding(t *testing.T) {1356+ p := Plain1357+ assert.Equal(t, "plain", p.Name())1358+1359+ var s string1360+ req := requestWithBody("POST", "/", "test string")1361+ assert.NoError(t, p.Bind(req, &s))1362+ assert.Equal(t, s, "test string")1363+1364+ var bs []byte1365+ req = requestWithBody("POST", "/", "test []byte")1366+ assert.NoError(t, p.Bind(req, &bs))1367+ assert.Equal(t, bs, []byte("test []byte"))1368+1369+ var i int1370+ req = requestWithBody("POST", "/", "test fail")1371+ assert.Error(t, p.Bind(req, &i))1372+1373+ req = requestWithBody("POST", "/", "")1374+ req.Body = &failRead{}1375+ assert.Error(t, p.Bind(req, &s))1376+1377+ req = requestWithBody("POST", "/", "")1378+ assert.Nil(t, p.Bind(req, nil))1379+1380+ var ptr *string1381+ req = requestWithBody("POST", "/", "")1382+ assert.Nil(t, p.Bind(req, ptr))1383+}1384+1385 func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1386 assert.Equal(t, name, b.Name())1387 1388 obj := protoexample.Test{}25 unmodified linesmodified:binding/binding.go+1 added
82 unmodified lines83 MsgPack BindingBody = msgpackBinding{}84 YAML BindingBody = yamlBinding{}85 Uri BindingUri = uriBinding{}86 Header Binding = headerBinding{}87+ Plain BindingBody = plainBinding{}88 TOML BindingBody = tomlBinding{}89 )90 91 // Default returns the appropriate Binding instance based on the HTTP method32 unmodified linesadded:binding/plain.go+56 added
1+package binding2+3+import (4+ "fmt"5+ "io"6+ "net/http"7+ "reflect"8+9+ "github.com/gin-gonic/gin/internal/bytesconv"10+)11+12+type plainBinding struct{}13+14+func (plainBinding) Name() string {15+ return "plain"16+}17+18+func (plainBinding) Bind(req *http.Request, obj interface{}) error {19+ all, err := io.ReadAll(req.Body)20+ if err != nil {21+ return err22+ }23+24+ return decodePlain(all, obj)25+}26+27+func (plainBinding) BindBody(body []byte, obj any) error {28+ return decodePlain(body, obj)29+}30+31+func decodePlain(data []byte, obj any) error {32+ if obj == nil {33+ return nil34+ }35+36+ v := reflect.ValueOf(obj)37+38+ for v.Kind() == reflect.Ptr {39+ if v.IsNil() {40+ return nil41+ }42+ v = v.Elem()43+ }44+45+ if v.Kind() == reflect.String {46+ v.SetString(bytesconv.BytesToString(data))47+ return nil48+ }49+50+ if _, ok := v.Interface().([]byte); ok {51+ v.SetBytes(data)52+ return nil53+ }54+55+ return fmt.Errorf("type (%T) unknown type", v)56+}modified:context_test.go+124 added
1668 unmodified lines1669 assert.Equal(t, "BAR", obj.Bar)1670 assert.Equal(t, 0, w.Body.Len())1671 }1672 1673+func TestContextBindPlain(t *testing.T) {1674+1675+ // string1676+ w := httptest.NewRecorder()1677+ c, _ := CreateTestContext(w)1678+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test string`))1679+ c.Request.Header.Add("Content-Type", MIMEPlain)1680+1681+ var s string1682+1683+ assert.NoError(t, c.BindPlain(&s))1684+ assert.Equal(t, "test string", s)1685+ assert.Equal(t, 0, w.Body.Len())1686+1687+ // []byte1688+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test []byte`))1689+ c.Request.Header.Add("Content-Type", MIMEPlain)1690+1691+ var bs []byte1692+1693+ assert.NoError(t, c.BindPlain(&bs))1694+ assert.Equal(t, []byte("test []byte"), bs)1695+ assert.Equal(t, 0, w.Body.Len())1696+}1697+1698 func TestContextBindHeader(t *testing.T) {1699 w := httptest.NewRecorder()1700 c, _ := CreateTestContext(w)1701 138 unmodified lines1840 assert.Equal(t, "BAR", obj.Bar)1841 assert.Equal(t, 0, w.Body.Len())1842 }1843 1844+func TestContextShouldBindPlain(t *testing.T) {1845+ // string1846+ w := httptest.NewRecorder()1847+ c, _ := CreateTestContext(w)1848+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test string`))1849+ c.Request.Header.Add("Content-Type", MIMEPlain)1850+1851+ var s string1852+1853+ assert.NoError(t, c.ShouldBindPlain(&s))1854+ assert.Equal(t, "test string", s)1855+ assert.Equal(t, 0, w.Body.Len())1856+ // []byte1857+1858+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`test []byte`))1859+ c.Request.Header.Add("Content-Type", MIMEPlain)1860+1861+ var bs []byte1862+1863+ assert.NoError(t, c.ShouldBindPlain(&bs))1864+ assert.Equal(t, []byte("test []byte"), bs)1865+ assert.Equal(t, 0, w.Body.Len())1866+1867+}1868+1869 func TestContextShouldBindHeader(t *testing.T) {1870 w := httptest.NewRecorder()1871 c, _ := CreateTestContext(w)1872 423 unmodified lines2296 }2297 }2298 }2299 2300+func TestContextShouldBindBodyWithPlain(t *testing.T) {2301+ for _, tt := range []struct {2302+ name string2303+ bindingBody binding.BindingBody2304+ body string2305+ }{2306+ {2307+ name: " JSON & JSON-BODY ",2308+ bindingBody: binding.JSON,2309+ body: `{"foo":"FOO"}`,2310+ },2311+ {2312+ name: " JSON & XML-BODY ",2313+ bindingBody: binding.XML,2314+ body: `<?xml version="1.0" encoding="UTF-8"?>2315+<root>2316+<foo>FOO</foo>2317+</root>`,2318+ },2319+ {2320+ name: " JSON & YAML-BODY ",2321+ bindingBody: binding.YAML,2322+ body: `foo: FOO`,2323+ },2324+ {2325+ name: " JSON & TOM-BODY ",2326+ bindingBody: binding.TOML,2327+ body: `foo=FOO`,2328+ },2329+ {2330+ name: " JSON & Plain-BODY ",2331+ bindingBody: binding.Plain,2332+ body: `foo=FOO`,2333+ },2334+ } {2335+ t.Logf("testing: %s", tt.name)2336+2337+ w := httptest.NewRecorder()2338+ c, _ := CreateTestContext(w)2339+2340+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(tt.body))2341+2342+ type typeJSON struct {2343+ Foo string `json:"foo" binding:"required"`2344+ }2345+ objJSON := typeJSON{}2346+2347+ if tt.bindingBody == binding.Plain {2348+ body := ""2349+ assert.NoError(t, c.ShouldBindBodyWithPlain(&body))2350+ assert.Equal(t, body, "foo=FOO")2351+ }2352+2353+ if tt.bindingBody == binding.JSON {2354+ assert.NoError(t, c.ShouldBindBodyWithJSON(&objJSON))2355+ assert.Equal(t, typeJSON{"FOO"}, objJSON)2356+ }2357+2358+ if tt.bindingBody == binding.XML {2359+ assert.Error(t, c.ShouldBindBodyWithJSON(&objJSON))2360+ assert.Equal(t, typeJSON{}, objJSON)2361+ }2362+2363+ if tt.bindingBody == binding.YAML {2364+ assert.Error(t, c.ShouldBindBodyWithJSON(&objJSON))2365+ assert.Equal(t, typeJSON{}, objJSON)2366+ }2367+2368+ if tt.bindingBody == binding.TOML {2369+ assert.Error(t, c.ShouldBindBodyWithJSON(&objJSON))2370+ assert.Equal(t, typeJSON{}, objJSON)2371+ }2372+ }2373+}2374 func TestContextGolangContext(t *testing.T) {2375 c, _ := CreateTestContext(httptest.NewRecorder())2376 c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2377 assert.NoError(t, c.Err())473 unmodified linesmodified:context.go+16 added-1 removed
612 unmodified lines613 return err614 }615 defer src.Close()616 617- if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil {617+ if err = os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {618 return err619 }620 621 out, err := os.Create(dst)44 unmodified lines666 func (c *Context) BindTOML(obj any) error {667 return c.MustBindWith(obj, binding.TOML)668 }669 670+// BindPlain is a shortcut for c.MustBindWith(obj, binding.Plain).671+func (c *Context) BindPlain(obj any) error {672+ return c.MustBindWith(obj, binding.Plain)673+}674+675 // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).676 func (c *Context) BindHeader(obj any) error {677 return c.MustBindWith(obj, binding.Header)678 }57 unmodified lines736 func (c *Context) ShouldBindTOML(obj any) error {737 return c.ShouldBindWith(obj, binding.TOML)738 }739 740+// ShouldBindPlain is a shortcut for c.ShouldBindWith(obj, binding.Plain).741+func (c *Context) ShouldBindPlain(obj any) error {742+ return c.ShouldBindWith(obj, binding.Plain)743+}744+745 // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).746 func (c *Context) ShouldBindHeader(obj any) error {747 return c.ShouldBindWith(obj, binding.Header)748 }54 unmodified lines803 func (c *Context) ShouldBindBodyWithTOML(obj any) error {804 return c.ShouldBindBodyWith(obj, binding.TOML)805 }806 807+// ShouldBindBodyWithJSON is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).808+func (c *Context) ShouldBindBodyWithPlain(obj any) error {809+ return c.ShouldBindBodyWith(obj, binding.Plain)810+}811+812 // ClientIP implements one best effort algorithm to return the real client IP.813 // It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not.814 // If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]).815 // If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy,467 unmodified lines