gin/binding/binding.go
Bo-Yi Wu d43f6a591b
feat(render)!: make msgpack/bson/yaml/toml/protobuf opt-in subpackages
- Move MessagePack, BSON, YAML, TOML and ProtoBuf rendering and binding out
  of core into github.com/gin-gonic/gin/render/<format> subpackages
- Add content-type registries to binding and render that each subpackage
  populates from init() so ShouldBind and Negotiate keep negotiating
- Slim binding.Default to core types and resolve the rest via the registry
- Drop the obsolete nomsgpack build tag and binding_nomsgpack.go
- Cut a minimal JSON-only binary from 13MB to 6.5MB; non-core codecs now
  cost binary size only when their subpackage is imported

BREAKING CHANGE: c.YAML, c.TOML, c.ProtoBuf, c.BSON, c.BindYAML, c.BindTOML,
c.ShouldBindYAML, c.ShouldBindTOML, c.ShouldBindBodyWithYAML and
c.ShouldBindBodyWithTOML are removed, along with binding.MsgPack/BSON/YAML/
TOML/ProtoBuf, the render.MsgPack/BSON/YAML/TOML/ProtoBuf types and the
nomsgpack build tag. Import the matching github.com/gin-gonic/gin/render/<format>
subpackage and use its Render(c, code, obj) / ShouldBind(c, &obj) helpers
(or pass <format>.Binding to c.ShouldBindWith). Importing the subpackage also
re-registers the content type so c.ShouldBind and c.Negotiate work as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 22:30:25 +08:00

141 lines
5.0 KiB
Go

// Copyright 2014 Manu Martinez-Almeida. 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"
// Content-Type MIME of the most common data formats.
const (
MIMEJSON = "application/json"
MIMEHTML = "text/html"
MIMEXML = "application/xml"
MIMEXML2 = "text/xml"
MIMEPlain = "text/plain"
MIMEPOSTForm = "application/x-www-form-urlencoded"
MIMEMultipartPOSTForm = "multipart/form-data"
MIMEPROTOBUF = "application/x-protobuf"
MIMEMSGPACK = "application/x-msgpack"
MIMEMSGPACK2 = "application/msgpack"
MIMEYAML = "application/x-yaml"
MIMEYAML2 = "application/yaml"
MIMETOML = "application/toml"
MIMEBSON = "application/bson"
)
// Binding describes the interface which needs to be implemented for binding the
// data present in the request such as JSON request body, query parameters or
// the form POST.
type Binding interface {
Name() string
Bind(*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 {
Binding
BindBody([]byte, any) error
}
// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it reads the Params.
type BindingUri interface {
Name() string
BindUri(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
// https://github.com/go-playground/validator/tree/v10.6.1.
type StructValidator interface {
// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
// If the received type is a slice|array, the validation should be performed travel on every element.
// If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.
// If the received type is a struct or pointer to a struct, the validation should be performed.
// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
// Otherwise nil must be returned.
ValidateStruct(any) error
// Engine returns the underlying validator engine which powers the
// StructValidator implementation.
Engine() any
}
// Validator is the default validator which implements the StructValidator
// interface. It uses https://github.com/go-playground/validator/tree/v10.6.1
// under the hood.
var Validator StructValidator = &defaultValidator{}
// These implement the Binding interface and can be used to bind the data
// present in the request to struct instances.
//
// Bindings for non-core content types (MsgPack, BSON, YAML, TOML, ProtoBuf)
// are no longer registered here. Import the matching subpackage under
// github.com/gin-gonic/gin/render/<format> to opt in; its init() registers the
// binding with Default via Register so content-type negotiation keeps working.
var (
JSON BindingBody = jsonBinding{}
XML BindingBody = xmlBinding{}
Form Binding = formBinding{}
Query Binding = queryBinding{}
FormPost Binding = formPostBinding{}
FormMultipart Binding = formMultipartBinding{}
Uri BindingUri = uriBinding{}
Header Binding = headerBinding{}
Plain BindingBody = plainBinding{}
)
// registry maps a content type to the Binding registered for it by an optional
// format subpackage. It is only written from init() functions before main runs,
// so it needs no synchronization.
var registry = map[string]Binding{}
// Register associates a Binding with one content type so that Default (and
// therefore ShouldBind/Bind content-type negotiation) can resolve it. It is
// intended to be called from an init() function in a format subpackage, e.g.
// github.com/gin-gonic/gin/render/msgpack.
func Register(contentType string, b Binding) {
registry[contentType] = b
}
// Default returns the appropriate Binding instance based on the HTTP method
// and the content type. Content types served by an optional format subpackage
// are resolved through the registry populated by Register.
func Default(method, contentType string) Binding {
if method == http.MethodGet {
return Form
}
switch contentType {
case MIMEJSON:
return JSON
case MIMEXML, MIMEXML2:
return XML
case MIMEMultipartPOSTForm:
return FormMultipart
case MIMEPOSTForm:
return Form
}
if b, ok := registry[contentType]; ok {
return b
}
return Form
}
// Validate runs the registered StructValidator against obj. Format subpackages
// call it after decoding so that the `binding:""` struct tags keep working.
func Validate(obj any) error {
return validate(obj)
}
func validate(obj any) error {
if Validator == nil {
return nil
}
return Validator.ValidateStruct(obj)
}