Documentation
¶
Overview ¶
Package encoding turns values into bytes and back, in a content type chosen by configuration rather than by the call site.
It is not an HTTP package. HTTP was its first consumer and ServerEncoderDecoder still speaks in http.ResponseWriter and *http.Request, but the rest of the surface is transport-free and is meant to be used by anything that needs to encode data — queue payloads, cache entries, database columns, files on disk. Prefer it to calling json.Marshal directly, so that the content type stays one decision made in one place.
Picking a type to depend on ¶
The interfaces are layered so a caller can ask for the narrowest thing that does its job:
- Marshaler renders a value as bytes.
- Unmarshaler parses bytes into a value.
- Codec is both, plus the content type being spoken.
- ClientEncoder is a Codec that also streams, via io.Writer and io.Reader.
Depend on Marshaler or Codec unless a transport is genuinely part of the job.
For one-off use there are package-level helpers that build an encoder for you: Encode and Decode return errors, MustEncode and MustDecode panic, and each has a JSON-pinned variant (EncodeJSON, DecodeJSON, and so on) for callers whose wire format is fixed rather than configurable.
Bytes are exact ¶
Every encode path routes through one byte-oriented marshaler per content type, so EncodeJSON(v) returns exactly what json.Marshal(v) returns. In particular no trailing newline is appended — the streaming encoders in the standard library add one, and this package deliberately does not use them for that reason. Callers that store, compare, or checksum encoded bytes can rely on this.
Index ¶
- Constants
- Variables
- func ContentTypeToString(c ContentType) string
- func Decode(data []byte, ct *contentType, dest any) error
- func DecodeJSON(data []byte, dest any) error
- func Encode(data any, ct *contentType) ([]byte, error)
- func EncodeJSON(data any) ([]byte, error)
- func MustDecode(data []byte, ct *contentType, dest any)
- func MustDecodeJSON(data []byte, dest any)
- func MustEncode(data any, ct *contentType) []byte
- func MustEncodeJSON(data any) []byte
- func MustJSONIntoReader(data any) io.Reader
- func RegisterServerEncoderDecoder(i do.Injector)
- type ClientEncoder
- type Codec
- type Config
- type ContentType
- type Marshaler
- type Option
- type ServerEncoderDecoder
- type Unmarshaler
Constants ¶
const (
// ContentTypeHeaderKey is the HTTP standard header name for content type.
ContentTypeHeaderKey = "Content-type"
)
Variables ¶
var ( ContentTypes = []ContentType{ ContentTypeJSON, ContentTypeXML, ContentTypeTOML, ContentTypeYAML, ContentTypeEmoji, } )
Functions ¶
func ContentTypeToString ¶
func ContentTypeToString(c ContentType) string
ContentTypeToString allows a content type to be converted to a string.
func DecodeJSON ¶
func Encode ¶
Encode renders data in the given encoding, defaulting to JSON. It is the error-returning counterpart of Decode, and the entry point to reach for when something outside an HTTP handler needs bytes.
func EncodeJSON ¶
EncodeJSON JSON encodes a piece of data.
func MustDecode ¶
MustDecode encodes a given piece of data to a given encoding.
func MustDecodeJSON ¶
MustDecodeJSON JSON encodes a piece of data.
func MustEncode ¶
MustEncode encodes a given piece of data to a given encoding.
func MustEncodeJSON ¶
MustEncodeJSON JSON encodes a piece of data.
func MustJSONIntoReader ¶
MustJSONIntoReader JSON encodes a piece of data.
func RegisterServerEncoderDecoder ¶
RegisterServerEncoderDecoder registers a ContentType and ServerEncoderDecoder with the injector.
Types ¶
type ClientEncoder ¶
type ClientEncoder interface {
Codec
Encode(ctx context.Context, dest io.Writer, v any) error
EncodeReader(ctx context.Context, data any) (io.Reader, error)
}
ClientEncoder is a Codec that can also stream. The streaming halves are separated out because they are the parts tied to a transport; a caller that only needs bytes should ask for Marshaler or Codec instead.
func NewClientEncoder ¶
func NewClientEncoder(encoding *contentType, opts ...Option) ClientEncoder
NewClientEncoder provides a ClientEncoder.
type Codec ¶
type Codec interface {
Marshaler
Unmarshaler
ContentType() string
}
Codec is the transport-free pair, plus the content type it speaks. Prefer it over ClientEncoder wherever io.Writer and io.Reader are not part of the job.
type Config ¶
type Config struct {
ContentType string `env:"CONTENT_TYPE" json:"contentType" yaml:"contentType"`
// contains filtered or unexported fields
}
Config configures input/output encoding for the service.
type ContentType ¶
type ContentType *contentType
ContentType is the publicly accessible version of contentType.
var ( // ContentTypeJSON is to indicate we want JSON for some reason. ContentTypeJSON ContentType = buildContentType(contentTypeJSON) // ContentTypeXML is to indicate we want XML for some reason. ContentTypeXML ContentType = buildContentType(contentTypeXML) // ContentTypeTOML is to indicate we want TOML for some reason. ContentTypeTOML ContentType = buildContentType(contentTypeTOML) // ContentTypeYAML is to indicate we want YAML for some reason. ContentTypeYAML ContentType = buildContentType(contentTypeYAML) // ContentTypeEmoji is to indicate we want Emoji for some reason. ContentTypeEmoji ContentType = buildContentType(contentTypeEmoji) )
func NewContentType ¶
func NewContentType(cfg Config) ContentType
NewContentType provides a ContentType from a Config.
type Marshaler ¶
Marshaler renders a value as bytes in one content type. It is the smallest thing most callers need, and it carries no transport: anything that has to turn a value into bytes — a queue payload, a cache entry, a database column — should depend on this rather than on ClientEncoder.
type Option ¶
type Option func(*options)
Option configures the encoders this package constructs. The zero configuration works: an absent logger logs nowhere and an absent tracer provider traces nowhere.
func WithTracerProvider ¶
func WithTracerProvider(tracerProvider tracing.TracerProvider) Option
WithTracerProvider attaches a tracer provider, enabling spans on every encode and decode.
type ServerEncoderDecoder ¶
type ServerEncoderDecoder interface {
EncodeResponseWithStatus(ctx context.Context, res http.ResponseWriter, val any, statusCode int)
DecodeRequest(ctx context.Context, req *http.Request, dest any) error
DecodeBytes(ctx context.Context, payload []byte, dest any) error
MustEncode(ctx context.Context, v any) []byte
MustEncodeJSON(ctx context.Context, v any) []byte
}
ServerEncoderDecoder is an interface that allows for multiple implementations of HTTP response formats.
func NewServerEncoderDecoder ¶
func NewServerEncoderDecoder(contentType ContentType, opts ...Option) ServerEncoderDecoder
NewServerEncoderDecoder provides a ServerEncoderDecoder.