feat(binding): support binding without validation

This commit is contained in:
Kristian Ye 2026-09-16 22:33:10 +03:00
parent 5c6a15f8f9
commit f68cd88161
19 changed files with 651 additions and 48 deletions

View File

@ -34,6 +34,13 @@ type Binding interface {
Bind(*http.Request, any) error
}
// BindingNoValidate adds BindNoValidate to Binding. BindNoValidate decodes or
// maps request data without invoking Validator.
type BindingNoValidate interface {
Binding
BindNoValidate(*http.Request, any) error
}
// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface {
@ -41,6 +48,13 @@ type BindingBody interface {
BindBody([]byte, any) error
}
// BindingBodyNoValidate adds body binding without validation.
type BindingBodyNoValidate interface {
BindingBody
BindingNoValidate
BindBodyNoValidate([]byte, any) error
}
// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it reads the Params.
type BindingUri interface {
@ -48,6 +62,12 @@ type BindingUri interface {
BindUri(map[string][]string, any) error
}
// BindingUriNoValidate adds URI binding without validation.
type BindingUriNoValidate interface {
BindingUri
BindUriNoValidate(map[string][]string, any) error
}
// StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness
// of the request. Gin provides a default implementation for this using
@ -74,20 +94,20 @@ var Validator StructValidator = &defaultValidator{}
// These implement the Binding interface and can be used to bind the data
// present in the request to struct instances.
var (
JSON BindingBody = jsonBinding{}
XML BindingBody = xmlBinding{}
Form Binding = formBinding{}
Query Binding = queryBinding{}
FormPost Binding = formPostBinding{}
FormMultipart Binding = formMultipartBinding{}
ProtoBuf BindingBody = protobufBinding{}
MsgPack BindingBody = msgpackBinding{}
YAML BindingBody = yamlBinding{}
Uri BindingUri = uriBinding{}
Header Binding = headerBinding{}
Plain BindingBody = plainBinding{}
TOML BindingBody = tomlBinding{}
BSON BindingBody = bsonBinding{}
JSON BindingBodyNoValidate = jsonBinding{}
XML BindingBodyNoValidate = xmlBinding{}
Form BindingNoValidate = formBinding{}
Query BindingNoValidate = queryBinding{}
FormPost BindingNoValidate = formPostBinding{}
FormMultipart BindingNoValidate = formMultipartBinding{}
ProtoBuf BindingBodyNoValidate = protobufBinding{}
MsgPack BindingBodyNoValidate = msgpackBinding{}
YAML BindingBodyNoValidate = yamlBinding{}
Uri BindingUriNoValidate = uriBinding{}
Header BindingNoValidate = headerBinding{}
Plain BindingBodyNoValidate = plainBinding{}
TOML BindingBodyNoValidate = tomlBinding{}
BSON BindingBodyNoValidate = bsonBinding{}
)
// Default returns the appropriate Binding instance based on the HTTP method

View File

@ -32,6 +32,13 @@ type Binding interface {
Bind(*http.Request, any) error
}
// BindingNoValidate adds BindNoValidate to Binding. BindNoValidate decodes or
// maps request data without invoking Validator.
type BindingNoValidate interface {
Binding
BindNoValidate(*http.Request, any) error
}
// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface {
@ -39,6 +46,13 @@ type BindingBody interface {
BindBody([]byte, any) error
}
// BindingBodyNoValidate adds body binding without validation.
type BindingBodyNoValidate interface {
BindingBody
BindingNoValidate
BindBodyNoValidate([]byte, any) error
}
// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it reads the Params.
type BindingUri interface {
@ -46,6 +60,12 @@ type BindingUri interface {
BindUri(map[string][]string, any) error
}
// BindingUriNoValidate adds URI binding without validation.
type BindingUriNoValidate interface {
BindingUri
BindUriNoValidate(map[string][]string, any) error
}
// StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness
// of the request. Gin provides a default implementation for this using
@ -71,19 +91,19 @@ var Validator StructValidator = &defaultValidator{}
// These implement the Binding interface and can be used to bind the data
// present in the request to struct instances.
var (
JSON = jsonBinding{}
XML = xmlBinding{}
Form = formBinding{}
Query = queryBinding{}
FormPost = formPostBinding{}
FormMultipart = formMultipartBinding{}
ProtoBuf = protobufBinding{}
YAML = yamlBinding{}
Uri = uriBinding{}
Header = headerBinding{}
TOML = tomlBinding{}
Plain = plainBinding{}
BSON BindingBody = bsonBinding{}
JSON BindingBodyNoValidate = jsonBinding{}
XML BindingBodyNoValidate = xmlBinding{}
Form BindingNoValidate = formBinding{}
Query BindingNoValidate = queryBinding{}
FormPost BindingNoValidate = formPostBinding{}
FormMultipart BindingNoValidate = formMultipartBinding{}
ProtoBuf BindingBodyNoValidate = protobufBinding{}
YAML BindingBodyNoValidate = yamlBinding{}
Uri BindingUriNoValidate = uriBinding{}
Header BindingNoValidate = headerBinding{}
TOML BindingBodyNoValidate = tomlBinding{}
Plain BindingBodyNoValidate = plainBinding{}
BSON BindingBodyNoValidate = bsonBinding{}
)
// Default returns the appropriate Binding instance based on the HTTP method

View File

@ -18,9 +18,13 @@ func (bsonBinding) Name() string {
}
func (b bsonBinding) Bind(req *http.Request, obj any) error {
return b.BindNoValidate(req, obj)
}
func (b bsonBinding) BindNoValidate(req *http.Request, obj any) error {
buf, err := io.ReadAll(req.Body)
if err == nil {
err = b.BindBody(buf, obj)
err = b.BindBodyNoValidate(buf, obj)
}
return err
}
@ -28,3 +32,7 @@ func (b bsonBinding) Bind(req *http.Request, obj any) error {
func (bsonBinding) BindBody(body []byte, obj any) error {
return bson.Unmarshal(body, obj)
}
func (bsonBinding) BindBodyNoValidate(body []byte, obj any) error {
return bson.Unmarshal(body, obj)
}

View File

@ -22,6 +22,13 @@ func (formBinding) Name() string {
}
func (formBinding) Bind(req *http.Request, obj any) error {
if err := (formBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (formBinding) BindNoValidate(req *http.Request, obj any) error {
if err := req.ParseForm(); err != nil {
return err
}
@ -31,7 +38,7 @@ func (formBinding) Bind(req *http.Request, obj any) error {
if err := mapForm(obj, req.Form); err != nil {
return err
}
return validate(obj)
return nil
}
func (formPostBinding) Name() string {
@ -39,13 +46,20 @@ func (formPostBinding) Name() string {
}
func (formPostBinding) Bind(req *http.Request, obj any) error {
if err := (formPostBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (formPostBinding) BindNoValidate(req *http.Request, obj any) error {
if err := req.ParseForm(); err != nil {
return err
}
if err := mapForm(obj, req.PostForm); err != nil {
return err
}
return validate(obj)
return nil
}
func (formMultipartBinding) Name() string {
@ -53,6 +67,13 @@ func (formMultipartBinding) Name() string {
}
func (formMultipartBinding) Bind(req *http.Request, obj any) error {
if err := (formMultipartBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (formMultipartBinding) BindNoValidate(req *http.Request, obj any) error {
if err := req.ParseMultipartForm(defaultMemory); err != nil {
return err
}
@ -60,5 +81,5 @@ func (formMultipartBinding) Bind(req *http.Request, obj any) error {
return err
}
return validate(obj)
return nil
}

View File

@ -17,11 +17,18 @@ func (headerBinding) Name() string {
}
func (headerBinding) Bind(req *http.Request, obj any) error {
if err := (headerBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (headerBinding) BindNoValidate(req *http.Request, obj any) error {
if err := mapHeader(obj, req.Header); err != nil {
return err
}
return validate(obj)
return nil
}
func mapHeader(ptr any, h map[string][]string) error {

View File

@ -31,17 +31,31 @@ func (jsonBinding) Name() string {
}
func (jsonBinding) Bind(req *http.Request, obj any) error {
if err := (jsonBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (jsonBinding) BindNoValidate(req *http.Request, obj any) error {
if req == nil || req.Body == nil {
return errors.New("invalid request")
}
return decodeJSON(req.Body, obj)
return decodeJSONNoValidate(req.Body, obj)
}
func (jsonBinding) BindBody(body []byte, obj any) error {
return decodeJSON(bytes.NewReader(body), obj)
if err := (jsonBinding{}).BindBodyNoValidate(body, obj); err != nil {
return err
}
return validate(obj)
}
func decodeJSON(r io.Reader, obj any) error {
func (jsonBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeJSONNoValidate(bytes.NewReader(body), obj)
}
func decodeJSONNoValidate(r io.Reader, obj any) error {
decoder := json.API.NewDecoder(r)
if EnableDecoderUseNumber {
decoder.UseNumber()
@ -52,5 +66,5 @@ func decodeJSON(r io.Reader, obj any) error {
if err := decoder.Decode(obj); err != nil {
return err
}
return validate(obj)
return nil
}

View File

@ -24,14 +24,26 @@ func (msgpackBinding) Bind(req *http.Request, obj any) error {
return decodeMsgPack(req.Body, obj)
}
func (msgpackBinding) BindNoValidate(req *http.Request, obj any) error {
return decodeMsgPackNoValidate(req.Body, obj)
}
func (msgpackBinding) BindBody(body []byte, obj any) error {
return decodeMsgPack(bytes.NewReader(body), obj)
}
func (msgpackBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeMsgPackNoValidate(bytes.NewReader(body), obj)
}
func decodeMsgPack(r io.Reader, obj any) error {
cdc := new(codec.MsgpackHandle)
if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {
if err := decodeMsgPackNoValidate(r, obj); err != nil {
return err
}
return validate(obj)
}
func decodeMsgPackNoValidate(r io.Reader, obj any) error {
cdc := new(codec.MsgpackHandle)
return codec.NewDecoder(r, cdc).Decode(&obj)
}

View File

@ -8,6 +8,7 @@ package binding
import (
"bytes"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
@ -25,6 +26,24 @@ func TestMsgpackBindingBindBody(t *testing.T) {
assert.Equal(t, "FOO", s.Foo)
}
func TestMsgpackBindingNoValidate(t *testing.T) {
type teststruct struct {
Foo string `msgpack:"foo"`
Required string `msgpack:"required" binding:"required"`
}
body := msgpackBody(t, teststruct{Foo: "FOO"})
var fromRequest teststruct
req := requestWithBody(http.MethodPost, "/", string(body))
require.NoError(t, msgpackBinding{}.BindNoValidate(req, &fromRequest))
assert.Equal(t, "FOO", fromRequest.Foo)
require.Error(t, Validator.ValidateStruct(&fromRequest))
var fromBody teststruct
require.NoError(t, msgpackBinding{}.BindBodyNoValidate(body, &fromBody))
assert.Equal(t, fromRequest, fromBody)
}
func msgpackBody(t *testing.T, obj any) []byte {
var bs bytes.Buffer
h := &codec.MsgpackHandle{}

View File

@ -0,0 +1,78 @@
// Copyright 2026 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"net/http"
"testing"
"github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestBodyBindingsWithoutValidation(t *testing.T) {
type formatRequest struct {
Name string `json:"name" xml:"name" yaml:"name" toml:"name"`
Required string `json:"required" xml:"required" yaml:"required" toml:"required" binding:"required"`
}
tests := []struct {
name string
body string
binder BindingBodyNoValidate
}{
{"JSON", `{"name":"Ada"}`, JSON},
{"XML", `<request><name>Ada</name></request>`, XML},
{"YAML", "name: Ada\n", YAML},
{"TOML", `name = "Ada"`, TOML},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var fromRequest formatRequest
req := requestWithBody(http.MethodPost, "/", tt.body)
require.NoError(t, tt.binder.BindNoValidate(req, &fromRequest))
require.Equal(t, "Ada", fromRequest.Name)
require.Error(t, Validator.ValidateStruct(&fromRequest))
var fromBody formatRequest
require.NoError(t, tt.binder.BindBodyNoValidate([]byte(tt.body), &fromBody))
require.Equal(t, fromRequest, fromBody)
})
}
var validated formatRequest
require.Error(t, JSON.BindBody([]byte(`{"name":"Ada"}`), &validated))
}
func TestPlainBindingWithoutValidation(t *testing.T) {
var fromRequest string
req := requestWithBody(http.MethodPost, "/", "hello")
require.NoError(t, Plain.BindNoValidate(req, &fromRequest))
require.Equal(t, "hello", fromRequest)
var fromBody string
require.NoError(t, Plain.BindBodyNoValidate([]byte("hello"), &fromBody))
require.Equal(t, fromRequest, fromBody)
}
func TestProtobufBindingWithoutValidation(t *testing.T) {
body, err := proto.Marshal(&protoexample.Test{Label: proto.String("yes")})
require.NoError(t, err)
var fromRequest protoexample.Test
req := requestWithBody(http.MethodPost, "/", string(body))
require.NoError(t, ProtoBuf.BindNoValidate(req, &fromRequest))
require.Equal(t, "yes", fromRequest.GetLabel())
var fromBody protoexample.Test
require.NoError(t, ProtoBuf.BindBodyNoValidate(body, &fromBody))
require.Equal(t, fromRequest.GetLabel(), fromBody.GetLabel())
var validated protoexample.Test
require.NoError(t, ProtoBuf.BindBody(body, &validated))
require.Equal(t, "yes", validated.GetLabel())
}

View File

@ -16,6 +16,10 @@ func (plainBinding) Name() string {
}
func (plainBinding) Bind(req *http.Request, obj any) error {
return (plainBinding{}).BindNoValidate(req, obj)
}
func (plainBinding) BindNoValidate(req *http.Request, obj any) error {
all, err := io.ReadAll(req.Body)
if err != nil {
return err
@ -28,6 +32,10 @@ func (plainBinding) BindBody(body []byte, obj any) error {
return decodePlain(body, obj)
}
func (plainBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodePlain(body, obj)
}
func decodePlain(data []byte, obj any) error {
if obj == nil {
return nil

View File

@ -19,14 +19,22 @@ func (protobufBinding) Name() string {
}
func (b protobufBinding) Bind(req *http.Request, obj any) error {
return b.BindNoValidate(req, obj)
}
func (b protobufBinding) BindNoValidate(req *http.Request, obj any) error {
buf, err := io.ReadAll(req.Body)
if err != nil {
return err
}
return b.BindBody(buf, obj)
return b.BindBodyNoValidate(buf, obj)
}
func (protobufBinding) BindBody(body []byte, obj any) error {
return (protobufBinding{}).BindBodyNoValidate(body, obj)
}
func (protobufBinding) BindBodyNoValidate(body []byte, obj any) error {
msg, ok := obj.(proto.Message)
if !ok {
return errors.New("obj is not ProtoMessage")

View File

@ -13,9 +13,16 @@ func (queryBinding) Name() string {
}
func (queryBinding) Bind(req *http.Request, obj any) error {
values := req.URL.Query()
if err := mapForm(obj, values); err != nil {
if err := (queryBinding{}).BindNoValidate(req, obj); err != nil {
return err
}
return validate(obj)
}
func (queryBinding) BindNoValidate(req *http.Request, obj any) error {
values := req.URL.Query()
if err := mapForm(obj, values); err != nil {
return err
}
return nil
}

View File

@ -22,14 +22,26 @@ func (tomlBinding) Bind(req *http.Request, obj any) error {
return decodeToml(req.Body, obj)
}
func (tomlBinding) BindNoValidate(req *http.Request, obj any) error {
return decodeTomlNoValidate(req.Body, obj)
}
func (tomlBinding) BindBody(body []byte, obj any) error {
return decodeToml(bytes.NewReader(body), obj)
}
func (tomlBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeTomlNoValidate(bytes.NewReader(body), obj)
}
func decodeToml(r io.Reader, obj any) error {
decoder := toml.NewDecoder(r)
if err := decoder.Decode(obj); err != nil {
if err := decodeTomlNoValidate(r, obj); err != nil {
return err
}
return validate(obj)
}
func decodeTomlNoValidate(r io.Reader, obj any) error {
decoder := toml.NewDecoder(r)
return decoder.Decode(obj)
}

View File

@ -11,8 +11,15 @@ func (uriBinding) Name() string {
}
func (uriBinding) BindUri(m map[string][]string, obj any) error {
if err := mapURI(obj, m); err != nil {
if err := (uriBinding{}).BindUriNoValidate(m, obj); err != nil {
return err
}
return validate(obj)
}
func (uriBinding) BindUriNoValidate(m map[string][]string, obj any) error {
if err := mapURI(obj, m); err != nil {
return err
}
return nil
}

View File

@ -21,14 +21,26 @@ func (xmlBinding) Bind(req *http.Request, obj any) error {
return decodeXML(req.Body, obj)
}
func (xmlBinding) BindNoValidate(req *http.Request, obj any) error {
return decodeXMLNoValidate(req.Body, obj)
}
func (xmlBinding) BindBody(body []byte, obj any) error {
return decodeXML(bytes.NewReader(body), obj)
}
func (xmlBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeXMLNoValidate(bytes.NewReader(body), obj)
}
func decodeXML(r io.Reader, obj any) error {
decoder := xml.NewDecoder(r)
if err := decoder.Decode(obj); err != nil {
if err := decodeXMLNoValidate(r, obj); err != nil {
return err
}
return validate(obj)
}
func decodeXMLNoValidate(r io.Reader, obj any) error {
decoder := xml.NewDecoder(r)
return decoder.Decode(obj)
}

View File

@ -22,14 +22,26 @@ func (yamlBinding) Bind(req *http.Request, obj any) error {
return decodeYAML(req.Body, obj)
}
func (yamlBinding) BindNoValidate(req *http.Request, obj any) error {
return decodeYAMLNoValidate(req.Body, obj)
}
func (yamlBinding) BindBody(body []byte, obj any) error {
return decodeYAML(bytes.NewReader(body), obj)
}
func (yamlBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeYAMLNoValidate(bytes.NewReader(body), obj)
}
func decodeYAML(r io.Reader, obj any) error {
decoder := yaml.NewDecoder(r)
if err := decoder.Decode(obj); err != nil {
if err := decodeYAMLNoValidate(r, obj); err != nil {
return err
}
return validate(obj)
}
func decodeYAMLNoValidate(r io.Reader, obj any) error {
decoder := yaml.NewDecoder(r)
return decoder.Decode(obj)
}

199
binding_no_validate_test.go Normal file
View File

@ -0,0 +1,199 @@
// Copyright 2026 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/require"
)
var (
_ binding.BindingNoValidate = binding.JSON
_ binding.BindingNoValidate = binding.XML
_ binding.BindingNoValidate = binding.Form
_ binding.BindingNoValidate = binding.Query
_ binding.BindingNoValidate = binding.FormPost
_ binding.BindingNoValidate = binding.FormMultipart
_ binding.BindingNoValidate = binding.ProtoBuf
_ binding.BindingNoValidate = binding.YAML
_ binding.BindingNoValidate = binding.Header
_ binding.BindingNoValidate = binding.Plain
_ binding.BindingNoValidate = binding.TOML
_ binding.BindingNoValidate = binding.BSON
_ binding.BindingBodyNoValidate = binding.JSON
_ binding.BindingBodyNoValidate = binding.XML
_ binding.BindingBodyNoValidate = binding.ProtoBuf
_ binding.BindingBodyNoValidate = binding.YAML
_ binding.BindingBodyNoValidate = binding.Plain
_ binding.BindingBodyNoValidate = binding.TOML
_ binding.BindingBodyNoValidate = binding.BSON
_ binding.BindingUriNoValidate = binding.Uri
)
type deferredBindingRequest struct {
ID string `uri:"id" binding:"required"`
Name string `json:"name" binding:"required"`
Token string `header:"X-Token" binding:"required"`
}
func newNoValidateContext(method, target, body, contentType string) *Context {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(method, target, strings.NewReader(body))
c.Request.Header.Set("Content-Type", contentType)
return c
}
func TestShouldBindNoValidateCombinesSources(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/users/42", `{"name":"Ada"}`, binding.MIMEJSON)
c.Params = Params{{Key: "id", Value: "42"}}
c.Request.Header.Set("X-Token", "secret")
validator := binding.Validator
var got deferredBindingRequest
require.NoError(t, c.ShouldBindUriNoValidate(&got))
require.NoError(t, c.ShouldBindJSONNoValidate(&got))
require.NoError(t, c.ShouldBindHeaderNoValidate(&got))
require.Equal(t, deferredBindingRequest{ID: "42", Name: "Ada", Token: "secret"}, got)
require.NoError(t, binding.Validator.ValidateStruct(&got))
require.Same(t, validator, binding.Validator)
}
func TestShouldBindNoValidateLeavesValidationExplicit(t *testing.T) {
withoutValidation := newNoValidateContext(http.MethodPost, "/", `{"name":"Ada"}`, binding.MIMEJSON)
var partiallyBound deferredBindingRequest
require.NoError(t, withoutValidation.ShouldBindNoValidate(&partiallyBound))
require.Error(t, binding.Validator.ValidateStruct(&partiallyBound))
withValidation := newNoValidateContext(http.MethodPost, "/", `{"name":"Ada"}`, binding.MIMEJSON)
var validated deferredBindingRequest
require.Error(t, withValidation.ShouldBind(&validated))
}
func TestShouldBindNoValidateStillReturnsDecodeErrors(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/", `{"name":`, binding.MIMEJSON)
var got deferredBindingRequest
require.Error(t, c.ShouldBindJSONNoValidate(&got))
}
func TestShouldBindQueryNoValidateLeavesValidationExplicit(t *testing.T) {
type queryRequest struct {
Page int `form:"page" binding:"required,min=1"`
Size int `form:"size" binding:"required,min=1"`
}
c := newNoValidateContext(http.MethodGet, "/?page=3", "", binding.MIMEPOSTForm)
var got queryRequest
require.NoError(t, c.ShouldBindQueryNoValidate(&got))
require.Equal(t, 3, got.Page)
require.Zero(t, got.Size)
require.Error(t, binding.Validator.ValidateStruct(&got))
}
func TestShouldBindBodyWithNoValidateReusesBody(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/", `{"name":"Ada"}`, binding.MIMEJSON)
var first, second deferredBindingRequest
require.NoError(t, c.ShouldBindBodyWithJSONNoValidate(&first))
require.NoError(t, c.ShouldBindBodyWithJSONNoValidate(&second))
require.Equal(t, first, second)
require.Equal(t, "Ada", second.Name)
}
type failingNoValidateBody struct{}
func (failingNoValidateBody) Read([]byte) (int, error) {
return 0, errors.New("read failed")
}
func (failingNoValidateBody) Close() error { return nil }
func TestShouldBindBodyWithNoValidateReturnsReadError(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/", "", binding.MIMEJSON)
c.Request.Body = failingNoValidateBody{}
var got deferredBindingRequest
require.EqualError(t, c.ShouldBindBodyWithJSONNoValidate(&got), "read failed")
}
func TestShouldBindNoValidateFormatShortcuts(t *testing.T) {
type formatRequest struct {
Name string `xml:"name" yaml:"name" toml:"name"`
Required string `xml:"required" yaml:"required" toml:"required" binding:"required"`
}
tests := []struct {
name string
body string
contentType string
bind func(*Context, any) error
bindBody func(*Context, any) error
bodyBinding binding.BindingBodyNoValidate
}{
{"XML", `<request><name>Ada</name></request>`, binding.MIMEXML, (*Context).ShouldBindXMLNoValidate, (*Context).ShouldBindBodyWithXMLNoValidate, binding.XML},
{"YAML", "name: Ada\n", binding.MIMEYAML, (*Context).ShouldBindYAMLNoValidate, (*Context).ShouldBindBodyWithYAMLNoValidate, binding.YAML},
{"TOML", `name = "Ada"`, binding.MIMETOML, (*Context).ShouldBindTOMLNoValidate, (*Context).ShouldBindBodyWithTOMLNoValidate, binding.TOML},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/", tt.body, tt.contentType)
var direct formatRequest
require.NoError(t, tt.bind(c, &direct))
require.Equal(t, "Ada", direct.Name)
require.Error(t, binding.Validator.ValidateStruct(&direct))
c = newNoValidateContext(http.MethodPost, "/", tt.body, tt.contentType)
var first, second formatRequest
require.NoError(t, tt.bindBody(c, &first))
require.NoError(t, c.ShouldBindBodyWithNoValidate(&second, tt.bodyBinding))
require.Equal(t, first, second)
})
}
}
func TestShouldBindNoValidatePlainShortcuts(t *testing.T) {
c := newNoValidateContext(http.MethodPost, "/", "hello", binding.MIMEPlain)
var direct string
require.NoError(t, c.ShouldBindPlainNoValidate(&direct))
require.Equal(t, "hello", direct)
c = newNoValidateContext(http.MethodPost, "/", "hello", binding.MIMEPlain)
var first, second string
require.NoError(t, c.ShouldBindBodyWithPlainNoValidate(&first))
require.NoError(t, c.ShouldBindBodyWithNoValidate(&second, binding.Plain))
require.Equal(t, first, second)
}
type customNoValidateBinding struct{}
func (customNoValidateBinding) Name() string { return "custom" }
func (customNoValidateBinding) Bind(*http.Request, any) error {
return errors.New("validated binding path called")
}
func (customNoValidateBinding) BindNoValidate(_ *http.Request, obj any) error {
value, ok := obj.(*string)
if !ok {
return errors.New("expected *string")
}
*value = "bound"
return nil
}
func TestShouldBindWithNoValidateUsesCustomBinder(t *testing.T) {
c := newNoValidateContext(http.MethodGet, "/", "", "")
var got string
require.NoError(t, c.ShouldBindWithNoValidate(&got, customNoValidateBinding{}))
require.Equal(t, "bound", got)
}

View File

@ -863,6 +863,14 @@ func (c *Context) ShouldBind(obj any) error {
return c.ShouldBindWith(obj, b)
}
// ShouldBindNoValidate selects a binding engine from the request and binds
// into obj without invoking binding.Validator.
func (c *Context) ShouldBindNoValidate(obj any) error {
// Every built-in returned by binding.Default implements BindingNoValidate.
b := binding.Default(c.Request.Method, c.ContentType()).(binding.BindingNoValidate)
return c.ShouldBindWithNoValidate(obj, b)
}
// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
//
// Example:
@ -891,42 +899,77 @@ func (c *Context) ShouldBindJSON(obj any) error {
return c.ShouldBindWith(obj, binding.JSON)
}
// ShouldBindJSONNoValidate binds JSON without invoking binding.Validator.
func (c *Context) ShouldBindJSONNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.JSON)
}
// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
// It works like ShouldBindJSON but binds the request body as XML data.
func (c *Context) ShouldBindXML(obj any) error {
return c.ShouldBindWith(obj, binding.XML)
}
// ShouldBindXMLNoValidate binds XML without invoking binding.Validator.
func (c *Context) ShouldBindXMLNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.XML)
}
// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
// It works like ShouldBindJSON but binds query parameters from the URL.
func (c *Context) ShouldBindQuery(obj any) error {
return c.ShouldBindWith(obj, binding.Query)
}
// ShouldBindQueryNoValidate binds query parameters without invoking binding.Validator.
func (c *Context) ShouldBindQueryNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.Query)
}
// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).
// It works like ShouldBindJSON but binds the request body as YAML data.
func (c *Context) ShouldBindYAML(obj any) error {
return c.ShouldBindWith(obj, binding.YAML)
}
// ShouldBindYAMLNoValidate binds YAML without invoking binding.Validator.
func (c *Context) ShouldBindYAMLNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.YAML)
}
// ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML).
// It works like ShouldBindJSON but binds the request body as TOML data.
func (c *Context) ShouldBindTOML(obj any) error {
return c.ShouldBindWith(obj, binding.TOML)
}
// ShouldBindTOMLNoValidate binds TOML without invoking binding.Validator.
func (c *Context) ShouldBindTOMLNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.TOML)
}
// ShouldBindPlain is a shortcut for c.ShouldBindWith(obj, binding.Plain).
// It works like ShouldBindJSON but binds plain text data from the request body.
func (c *Context) ShouldBindPlain(obj any) error {
return c.ShouldBindWith(obj, binding.Plain)
}
// ShouldBindPlainNoValidate binds plain text without invoking binding.Validator.
func (c *Context) ShouldBindPlainNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.Plain)
}
// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).
// It works like ShouldBindJSON but binds values from HTTP headers.
func (c *Context) ShouldBindHeader(obj any) error {
return c.ShouldBindWith(obj, binding.Header)
}
// ShouldBindHeaderNoValidate binds headers without invoking binding.Validator.
func (c *Context) ShouldBindHeaderNoValidate(obj any) error {
return c.ShouldBindWithNoValidate(obj, binding.Header)
}
// ShouldBindUri binds the passed struct pointer using the specified binding engine.
// It works like ShouldBindJSON but binds parameters from the URI.
func (c *Context) ShouldBindUri(obj any) error {
@ -937,12 +980,26 @@ func (c *Context) ShouldBindUri(obj any) error {
return binding.Uri.BindUri(m, obj)
}
// ShouldBindUriNoValidate binds URI parameters without invoking binding.Validator.
func (c *Context) ShouldBindUriNoValidate(obj any) error {
m := make(map[string][]string, len(c.Params))
for _, v := range c.Params {
m[v.Key] = []string{v.Value}
}
return binding.Uri.BindUriNoValidate(m, obj)
}
// 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 {
return b.Bind(c.Request, obj)
}
// ShouldBindWithNoValidate binds with b without invoking binding.Validator.
func (c *Context) ShouldBindWithNoValidate(obj any, b binding.BindingNoValidate) error {
return b.BindNoValidate(c.Request, obj)
}
// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
// body into the context, and reuse when it is called again.
//
@ -965,31 +1022,75 @@ func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error
return bb.BindBody(body, obj)
}
// ShouldBindBodyWithNoValidate is like ShouldBindBodyWith, but it does not
// invoke binding.Validator after decoding the cached body.
func (c *Context) ShouldBindBodyWithNoValidate(obj any, bb binding.BindingBodyNoValidate) (err error) {
var body []byte
if cb, ok := c.Get(BodyBytesKey); ok {
if cbb, ok := cb.([]byte); ok {
body = cbb
}
}
if body == nil {
body, err = io.ReadAll(c.Request.Body)
if err != nil {
return err
}
c.Set(BodyBytesKey, body)
}
return bb.BindBodyNoValidate(body, obj)
}
// ShouldBindBodyWithJSON is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).
func (c *Context) ShouldBindBodyWithJSON(obj any) error {
return c.ShouldBindBodyWith(obj, binding.JSON)
}
// ShouldBindBodyWithJSONNoValidate binds a reusable JSON body without validation.
func (c *Context) ShouldBindBodyWithJSONNoValidate(obj any) error {
return c.ShouldBindBodyWithNoValidate(obj, binding.JSON)
}
// ShouldBindBodyWithXML is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).
func (c *Context) ShouldBindBodyWithXML(obj any) error {
return c.ShouldBindBodyWith(obj, binding.XML)
}
// ShouldBindBodyWithXMLNoValidate binds a reusable XML body without validation.
func (c *Context) ShouldBindBodyWithXMLNoValidate(obj any) error {
return c.ShouldBindBodyWithNoValidate(obj, binding.XML)
}
// ShouldBindBodyWithYAML is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).
func (c *Context) ShouldBindBodyWithYAML(obj any) error {
return c.ShouldBindBodyWith(obj, binding.YAML)
}
// ShouldBindBodyWithYAMLNoValidate binds a reusable YAML body without validation.
func (c *Context) ShouldBindBodyWithYAMLNoValidate(obj any) error {
return c.ShouldBindBodyWithNoValidate(obj, binding.YAML)
}
// ShouldBindBodyWithTOML is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).
func (c *Context) ShouldBindBodyWithTOML(obj any) error {
return c.ShouldBindBodyWith(obj, binding.TOML)
}
// ShouldBindBodyWithTOMLNoValidate binds a reusable TOML body without validation.
func (c *Context) ShouldBindBodyWithTOMLNoValidate(obj any) error {
return c.ShouldBindBodyWithNoValidate(obj, binding.TOML)
}
// ShouldBindBodyWithPlain is a shortcut for c.ShouldBindBodyWith(obj, binding.Plain).
func (c *Context) ShouldBindBodyWithPlain(obj any) error {
return c.ShouldBindBodyWith(obj, binding.Plain)
}
// ShouldBindBodyWithPlainNoValidate binds a reusable plain body without validation.
func (c *Context) ShouldBindBodyWithPlainNoValidate(obj any) error {
return c.ShouldBindBodyWithNoValidate(obj, binding.Plain)
}
// ClientIP implements one best effort algorithm to return the real client IP.
// It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not.
// If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-IP]).

View File

@ -34,6 +34,7 @@
- [Request Binding & Validation](#request-binding--validation)
- [Model binding and validation](#model-binding-and-validation)
- [Custom Validators](#custom-validators)
- [Bind from multiple sources before validation](#bind-from-multiple-sources-before-validation)
- [Only Bind Query String](#only-bind-query-string)
- [Bind Query String or Post Data](#bind-query-string-or-post-data)
- [Bind default value if none provided](#bind-default-value-if-none-provided)
@ -996,6 +997,43 @@ $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"
[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.
See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.
### Bind from multiple sources before validation
The standard binding methods validate after every bind. When one struct is populated from several request sources, use the `NoValidate` variants and validate the completed value explicitly:
```go
type UpdateUserRequest struct {
ID string `uri:"id" binding:"required"`
Name string `json:"name" binding:"required"`
Token string `header:"X-Token" binding:"required"`
}
func updateUser(c *gin.Context) {
var request UpdateUserRequest
if err := c.ShouldBindUriNoValidate(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := c.ShouldBindJSONNoValidate(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := c.ShouldBindHeaderNoValidate(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := binding.Validator.ValidateStruct(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.Status(http.StatusNoContent)
}
```
No-validation binding still returns decoding and mapping errors. It only defers struct validation and does not change the global validator.
### Only Bind Query String
`ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017).