Documentation
¶
Overview ¶
Package codec provides an HTTP middleware that performs automatic content negotiation using the encoding registry.
The middleware inspects the incoming Content-Type header, resolves it to a registered encoding.Codec, and stores that codec in the request context. Handler code can then use the helper functions FromContext, ReadBody, and Respond to unmarshal requests and marshal responses without hardcoding a specific serialization format.
Usage:
import (
"github.com/tx7do/go-wind-plugins/transport/http/middleware/codec"
_ "github.com/tx7do/go-wind-plugins/encoding/json" // register JSON codec
_ "github.com/tx7do/go-wind-plugins/encoding/xml" // register XML codec
)
srv.Use(codec.Middleware())
// In a handler:
func(w http.ResponseWriter, r *http.Request) {
var req MyRequest
if err := codec.ReadBody(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp := process(&req)
codec.Respond(w, r, http.StatusOK, resp)
}
Index ¶
- Variables
- func FromContext(ctx context.Context) encoding.Codec
- func Middleware(opts ...Option) httpPlugin.Middleware
- func ReadBody(r *http.Request, target any) error
- func RegisterMimeType(mime, codecName string)
- func Respond(w http.ResponseWriter, r *http.Request, statusCode int, data any) error
- type Option
Constants ¶
This section is empty.
Variables ¶
var ErrCodecNotFound = errors.New("codec: no codec found in context (middleware not registered?)")
ErrCodecNotFound is returned when no codec is registered in the context.
Functions ¶
func FromContext ¶
FromContext returns the encoding.Codec stored in the request context. Returns nil if the middleware was not registered.
func Middleware ¶
func Middleware(opts ...Option) httpPlugin.Middleware
Middleware returns a httpPlugin.Middleware that resolves the request's Content-Type header to an encoding.Codec and stores it in the request context.
Handlers retrieve the codec with FromContext and use ReadBody / Respond for automatic (un)marshalling.
func ReadBody ¶
ReadBody reads the request body and unmarshals it into target using the codec from the request context.
The request body is consumed and replaced with a new reader so that downstream code can still access it if needed.
func RegisterMimeType ¶
func RegisterMimeType(mime, codecName string)
RegisterMimeType associates a MIME type with a codec name. This allows applications to add custom MIME type mappings.