mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-26 11:28:17 +08:00
- 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>
33 lines
1.2 KiB
Go
33 lines
1.2 KiB
Go
// Copyright 2025 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 render
|
|
|
|
// Factory builds a Render for the given data. Optional format subpackages
|
|
// (github.com/gin-gonic/gin/render/<format>) register one per content type so
|
|
// that Context.Negotiate can produce their Render without the core importing
|
|
// the underlying codec library.
|
|
type Factory func(data any) Render
|
|
|
|
// registry maps a content type to its Factory. It is only written from init()
|
|
// functions before main runs, so it needs no synchronization.
|
|
var registry = map[string]Factory{}
|
|
|
|
// Register associates a Factory with a content type. It is intended to be
|
|
// called from an init() function in a format subpackage.
|
|
func Register(contentType string, factory Factory) {
|
|
registry[contentType] = factory
|
|
}
|
|
|
|
// Negotiate returns a Render for the content type and data when a Factory has
|
|
// been registered for it (i.e. the matching format subpackage was imported).
|
|
// The boolean reports whether a Factory was found.
|
|
func Negotiate(contentType string, data any) (Render, bool) {
|
|
factory, ok := registry[contentType]
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
return factory(data), true
|
|
}
|