Skip to content

Commit

Permalink
Merge branch 'master' into dependabot/go_modules/gorm.io/gorm-1.23.4
Browse files Browse the repository at this point in the history
  • Loading branch information
yinheli authored Apr 6, 2022
2 parents e85f3f2 + 99bc1c0 commit c9dede7
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ require (
gopkg.in/natefinch/lumberjack.v2 v2.0.0
gopkg.in/yaml.v2 v2.4.0
gorm.io/datatypes v1.0.6
gorm.io/driver/mysql v1.3.2
gorm.io/driver/mysql v1.3.3
gorm.io/gorm v1.23.4
gorm.io/plugin/opentracing v0.0.0-20211220013347-7d2b2af23560
)
25 changes: 25 additions & 0 deletions pkg/echox/query_binder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package echox

import "github.com/labstack/echo/v4"

// UseDefaultQueryBinder change behavior of query binder to use default binder
// enable always bind query params
// cause https://github.com/labstack/echo/issues/1670 disable bind query params for POST/PUT methods
func UseDefaultQueryBinder(e *echo.Echo) {
e.Binder = &defaultQueryBinder{
binder: e.Binder,
defaultBinder: new(echo.DefaultBinder),
}
}

type defaultQueryBinder struct {
binder echo.Binder
defaultBinder *echo.DefaultBinder
}

func (b *defaultQueryBinder) Bind(i interface{}, c echo.Context) error {
if err := b.defaultBinder.BindQueryParams(c, i); err != nil {
return err
}
return b.binder.Bind(i, c)
}
51 changes: 51 additions & 0 deletions pkg/echox/query_binder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package echox

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func Test_query_binder_query_param(t *testing.T) {
type Foo struct {
Id int `json:"id"`
Name string `json:"name" query:"name"`
}

build := func() (*echo.Echo, *httptest.ResponseRecorder, echo.Context) {
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/api/endpoint?name=foo", strings.NewReader(`{"id": 1}`))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
return e, rec, c
}

handler := func(c echo.Context) error {
var foo Foo
if err := c.Bind(&foo); err != nil {
return err
}
return c.JSON(http.StatusOK, foo)
}

e, rec, c := build()
err := handler(c)
require.NoError(t, err)
body := rec.Body.String()
assert.Contains(t, body, `"id":1`)
assert.Contains(t, body, `"name":""`)

e, rec, c = build()
UseDefaultQueryBinder(e)
err = handler(c)
require.NoError(t, err)
body = rec.Body.String()
assert.Contains(t, body, `"id":1`)
assert.Contains(t, body, `"name":"foo"`)
}

0 comments on commit c9dede7

Please sign in to comment.