encoding

package
v8.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

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

View Source
const (
	// ContentTypeHeaderKey is the HTTP standard header name for content type.
	ContentTypeHeaderKey = "Content-type"
)

Variables

Functions

func ContentTypeToString

func ContentTypeToString(c ContentType) string

ContentTypeToString allows a content type to be converted to a string.

func Decode

func Decode(data []byte, ct *contentType, dest any) error

func DecodeJSON

func DecodeJSON(data []byte, dest any) error

func Encode

func Encode(data any, ct *contentType) ([]byte, error)

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

func EncodeJSON(data any) ([]byte, error)

EncodeJSON JSON encodes a piece of data.

func MustDecode

func MustDecode(data []byte, ct *contentType, dest any)

MustDecode encodes a given piece of data to a given encoding.

func MustDecodeJSON

func MustDecodeJSON(data []byte, dest any)

MustDecodeJSON JSON encodes a piece of data.

func MustEncode

func MustEncode(data any, ct *contentType) []byte

MustEncode encodes a given piece of data to a given encoding.

func MustEncodeJSON

func MustEncodeJSON(data any) []byte

MustEncodeJSON JSON encodes a piece of data.

func MustJSONIntoReader

func MustJSONIntoReader(data any) io.Reader

MustJSONIntoReader JSON encodes a piece of data.

func RegisterServerEncoderDecoder

func RegisterServerEncoderDecoder(i do.Injector)

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.

func (*Config) ValidateWithContext

func (cfg *Config) ValidateWithContext(ctx context.Context) error

ValidateWithContext validates a Config struct.

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

type Marshaler interface {
	Marshal(ctx context.Context, v any) ([]byte, error)
}

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 WithLogger

func WithLogger(logger logging.Logger) Option

WithLogger attaches a logger.

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.

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(ctx context.Context, data []byte, v any) error
}

Unmarshaler parses bytes of one content type into v.

Directories

Path Synopsis
Package mockencoding provides moq-generated mocks for the encoding package.
Package mockencoding provides moq-generated mocks for the encoding package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL