Merge 303e21a421a36c1aa50ebb2266f32bd646b99d4d into 0397e5e0c0f8f8176c29f7edd8f1bff8e45df780

This commit is contained in:
Iliya 2024-04-08 15:18:25 -10:00 committed by GitHub
commit 1081fb359b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 66 additions and 0 deletions

View File

@ -672,6 +672,11 @@ func (c *Context) BindHeader(obj any) error {
return c.MustBindWith(obj, binding.Header)
}
// BindForm is a shortcut for c.MustBindWith(obj, binding.Form)
func (c *Context) BindForm(obj any) error {
return c.MustBindWith(obj, binding.Form)
}
// BindUri binds the passed struct pointer using binding.Uri.
// It will abort the request with HTTP 400 if any error occurs.
func (c *Context) BindUri(obj any) error {
@ -746,6 +751,11 @@ func (c *Context) ShouldBindUri(obj any) error {
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.
// See the binding package.
func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {

View File

@ -1657,6 +1657,62 @@ func TestContextBindWithXML(t *testing.T) {
assert.Equal(t, 0, w.Body.Len())
}
func TestContextBindForm(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest("POST", "/", nil)
if err := c.Request.ParseForm(); err != nil {
t.Error(err.Error())
}
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.BindForm(&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 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) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)