feature: add ShouldBindForm function

This commit is contained in:
iliya 2023-02-04 12:06:00 +03:30
parent 2cf4ce1085
commit 72f42b88a4
2 changed files with 32 additions and 0 deletions

View File

@ -740,6 +740,11 @@ func (c *Context) ShouldBindUri(obj any) error {
return binding.Uri.BindUri(m, obj) return binding.Uri.BindUri(m, obj)
} }
// ShouldBindForm is shortcut for c.ShouldBindWith(obj, binding.Form).
func (c *Context) ShouldBindForm(obj any) error {
return c.ShouldBindWith(obj, binding.Form)
}
// ShouldBindWith binds the passed struct pointer using the specified binding engine. // ShouldBindWith binds the passed struct pointer using the specified binding engine.
// See the binding package. // See the binding package.
func (c *Context) ShouldBindWith(obj any, b binding.Binding) error { func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {

View File

@ -1655,6 +1655,33 @@ func TestContextBindForm(t *testing.T) {
assert.Equal(t, 0, w.Body.Len()) assert.Equal(t, 0, w.Body.Len())
} }
func TestContextShouldBindForm(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest("POST", "/", nil)
c.Request.ParseForm()
c.Request.Form.Add("rate", "8000")
c.Request.Form.Add("domain", "music")
c.Request.Form.Add("limit", "1000")
var testHeader struct {
Rate int `form:"rate"`
Domain string `form:"domain"`
Limit int `form:"limit"`
Fake string `form:"fake"`
}
assert.NoError(t, c.ShouldBindForm(&testHeader))
assert.Equal(t, 8000, testHeader.Rate)
assert.Equal(t, "music", testHeader.Domain)
assert.Equal(t, 1000, testHeader.Limit)
assert.Equal(t, "", testHeader.Fake)
assert.Equal(t, 0, w.Body.Len())
}
func TestContextBindHeader(t *testing.T) { func TestContextBindHeader(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
c, _ := CreateTestContext(w) c, _ := CreateTestContext(w)