runtime

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 26 Imported by: 2

Documentation

Overview

Package runtime holds the helpers generated code imports. It uses the standard library only.

Index

Constants

View Source
const DateFormat = time.DateOnly

DateFormat is the layout of an OpenAPI date (RFC 3339 full-date).

View Source
const DefaultMultipartMemory = 32 << 20

DefaultMultipartMemory is how much of a multipart form stays in memory before parts spill to disk.

View Source
const SupportsGeneratorV1 = true

SupportsGeneratorV1 is set while this runtime has everything code from generator API level 1 uses. Generated files refer to it, so a runtime too old or too new for them fails to compile.

Variables

View Source
var (
	ErrInvalidDate        = errors.New("invalid date")
	ErrAdditionalProperty = errors.New("invalid additional property")

	ErrNoVariant            = errors.New("no union variant matches")
	ErrAmbiguous            = errors.New("more than one union variant matches")
	ErrUnknownDiscriminator = errors.New("unknown discriminator value")
	ErrNotObject            = errors.New("not a JSON object")

	ErrParamMissing = errors.New("parameter is required")
	ErrParamValue   = errors.New("invalid parameter value")
	ErrHeaderValue  = errors.New("invalid response header")
	ErrBodyEmpty    = errors.New("request body is required")
	ErrBodyValue    = errors.New("invalid body value")
	ErrContentType  = errors.New("unsupported content type")
)

Functions

func ContentType

func ContentType(h http.Header) string

ContentType is the media type of a request or response body, without its parameters. A parameter that does not parse, such as a charset without a value, leaves the media type.

func ContentTypeError

func ContentTypeError(mediaType string) error

ContentTypeError is the error of a body in a media type the operation does not take.

func DecodeBytes

func DecodeBytes(body io.Reader, isRequired bool) ([]byte, error)

DecodeBytes reads a body as it is.

func DecodeCookie

func DecodeCookie(cookies []*http.Cookie, p Param, dst any) error

DecodeCookie decodes a cookie into dst, a pointer to its type; a form cookie is percent-encoded.

func DecodeForm

func DecodeForm(body io.Reader, dst any, isRequired bool, enc Encoding) error

DecodeForm decodes an application/x-www-form-urlencoded body into dst, a pointer. Keys with brackets nest: address[city]=Berlin, items[0]=a. Into an untyped target, a value that reads as a number or a boolean becomes one. A field enc declares JSON is read as JSON.

func DecodeHeader

func DecodeHeader(h http.Header, p Param, dst any) error

DecodeHeader decodes a header into dst, a pointer to the parameter's type.

func DecodeHeaders

func DecodeHeaders(h http.Header, dst any) error

DecodeHeaders reads h into dst, a pointer to a struct of typed headers whose fields name their header in a json tag, each read as Headers writes it. A header that is not there leaves its field as it is.

func DecodeJSON

func DecodeJSON(body io.Reader, dst any, isRequired bool, unmarshal func(data []byte, v any) error) error

DecodeJSON decodes a JSON body into dst, a pointer, with unmarshal. An empty body is an error when the body is required, and leaves dst as it is otherwise.

func DecodeMultipart

func DecodeMultipart(r *http.Request, dst any, maxMemory int64, enc Encoding) error

DecodeMultipart decodes a multipart/form-data body into dst, a pointer to a struct. Fields of type File, *File or []File take the files of their name; a part that holds JSON fills a field of a struct, slice or map type; every other part is read as form text. maxMemory is how much stays in memory, DefaultMultipartMemory when 0. A type with UnmarshalForm reads the form itself. A part enc declares JSON is read as JSON.

func DecodeMultipartBody

func DecodeMultipartBody(body io.Reader, contentType string, dst any, enc Encoding) error

DecodeMultipartBody is DecodeMultipart for a body without its request, held in memory whole.

func DecodePath

func DecodePath(raw string, p Param, dst any) error

DecodePath decodes a path segment into dst, a pointer to the parameter's type.

func DecodeQuery

func DecodeQuery(q Query, p Param, dst any) error

DecodeQuery decodes a query parameter into dst, a pointer to the parameter's type. A parameter that is not there sets its default, else leaves dst as it is, unless it is required. A value that does not unescape is ErrParamValue.

func DecodeQueryString

func DecodeQueryString(raw string, p Param, dst any) error

DecodeQueryString decodes raw, the whole query, into dst: percent-encoded JSON or a form.

func DecodeText

func DecodeText(body io.Reader, isRequired bool) (string, error)

DecodeText reads a text body.

func DecodeTextValue

func DecodeTextValue(body io.Reader, dst any, isRequired bool) error

DecodeTextValue reads a text body into what dst points to, by its type, as EncodeText writes it.

func DiscriminatorError

func DiscriminatorError(_ []byte, err error) error

DiscriminatorError is the discriminator error of a MarshalVariants result, nil for any other.

func EncodeCookie

func EncodeCookie(v any, p Param) ([]*http.Cookie, error)

EncodeCookie writes v as cookies, one per item when exploded; a form cookie is percent-encoded.

func EncodeForm

func EncodeForm(v any, enc Encoding) (string, error)

EncodeForm writes v, a struct or a map, as a url-encoded form, each property as enc says.

func EncodeHeader

func EncodeHeader(v any, p Param) (string, error)

EncodeHeader writes v as a header value.

func EncodePath

func EncodePath(v any, p Param) (string, error)

EncodePath writes v as a path segment.

func EncodeQuery

func EncodeQuery(v any, p Param) (string, error)

EncodeQuery writes v as the query parameter p, name=value pairs joined by &, and "" for a nil value. It percent-encodes as RFC 6570 expands a form-style query: a separator goes as it is and the same byte inside a name or value escaped, a space as %20. With IsReserved, the reserved characters a query holds and %XX escapes stay as they are.

func EncodeText

func EncodeText(v any) (string, error)

EncodeText writes v, a scalar, as a text body carries it; another value is ErrContentType.

func ErrorMessage

func ErrorMessage(v any, path, fallback string) string

ErrorMessage returns the value at path in the JSON of v, or fallback when there is none. A path is dotted property names; a name ending in [] takes the first item of that array. A value that is no string is written as JSON.

func Headers

func Headers(h http.Header, v any) http.Header

Headers adds the fields of v, a struct of typed headers, to h and returns it, made when nil. A nil, unwritable or optional zero field is left out. Its header tag may say explode or json.

func IsJSON

func IsJSON(mediaType string) bool

IsJSON reports a JSON media type: application/json or one with a +json suffix.

func IsSequential

func IsSequential(mediaType string) bool

IsSequential reports a media type whose body is a sequence of frames: text/event-stream and the line-delimited JSON types, with or without parameters.

func MarshalAdditional

func MarshalAdditional[T any](fields any, extra map[string]T, known ...string) ([]byte, error)

MarshalAdditional writes fields, a struct whose additional properties are tagged json:"-", as a JSON object, then adds the entries of extra in key order. Keys in known, the struct's own property names, are left out of extra.

func MarshalOneOf

func MarshalOneOf(shared any, set ...any) ([]byte, error)

MarshalOneOf is MarshalUnion for a oneOf, where more than one set variant is an error.

func MarshalUnion

func MarshalUnion(shared any, set ...any) ([]byte, error)

MarshalUnion writes the set variants of a union merged with shared, its own properties or nil. When a part is no object, the first set variant is written alone; nothing set writes null.

func MarshalUnionText

func MarshalUnionText(data []byte, err error) ([]byte, error)

MarshalUnionText writes data, the JSON of a union of scalars, as text without string quotes.

func MarshalVariants

func MarshalVariants(shared any, u Union, variants ...any) ([]byte, error)

MarshalVariants is MarshalOneOf or MarshalUnion per union of u, filling or checking discriminators.

func MediaRange

func MediaRange(mediaType string) string

MediaRange is the range of one type a media type falls in, text/* for text/csv.

func MultipartSize

func MultipartSize(v any, enc Encoding) (int64, string, error)

MultipartSize writes v as a multipart form without reading its files, and returns the boundary it used with the length of the form, -1 when a file does not know its size.

func OperationID

func OperationID(ctx context.Context) string

OperationID returns the operation name ctx holds, or "" when it holds none.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to a copy of v.

func SetErrorMessage

func SetErrorMessage(dst any, path, message string) error

SetErrorMessage stores message at path in dst, a pointer, by decoding the JSON the path describes into it.

func UnescapePath

func UnescapePath(r *http.Request, v string) string

UnescapePath unescapes v, a path value a router cut from r.URL.RawPath when the request has one.

func UnmarshalAdditional

func UnmarshalAdditional[T any](data []byte, fields any, extra *map[string]T, known ...string) error

UnmarshalAdditional decodes data into fields, then every member whose key is not in known into extra, keeping the entries extra already has.

func UnmarshalAdditionalForm

func UnmarshalAdditionalForm[T any](form *multipart.Form, fields any, extra *map[string]T, known ...string) error

UnmarshalAdditionalForm reads form into fields, then every name not in known into extra.

func UnmarshalUnion

func UnmarshalUnion(data []byte, u Union) error

UnmarshalUnion decodes data into the variants of u it matches: one for oneOf, every match for anyOf. docs/types.md in the mockzilla-codegen repository has the order variants are tried in.

func UnmarshalUnionForm

func UnmarshalUnionForm(form *multipart.Form, fields any, u Union) error

UnmarshalUnionForm reads form into the shared fields, then into the variants it matches.

func UnmarshalUnionText

func UnmarshalUnionText(raw []byte, decode func(data []byte) error) error

UnmarshalUnionText decodes raw with a union's UnmarshalJSON, as a number or boolean first.

func WithOperationID

func WithOperationID(ctx context.Context, id string) context.Context

WithOperationID returns a copy of ctx that holds the name of the operation being called.

func WriteMultipart

func WriteMultipart(mw *multipart.Writer, v any, enc Encoding) error

WriteMultipart writes v, a struct, to mw as a multipart form and closes mw, which ends the form: File fields as file parts with their name and content type, application/octet-stream without one, lists as one part per item, structs and maps as JSON parts, bytes as base64, and everything else as text. A property enc declares a media type for is written in it. A nil slice or map is left out, and a zero field tagged omitempty or omitzero, as JSON leaves them out.

Types

type Date

type Date struct {
	time.Time
}

Date is a calendar date, written as 2006-01-02 in JSON and text.

func NewDate

func NewDate(year int, month time.Month, day int) Date

NewDate returns the date at midnight UTC.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON is needed because the embedded time.Time has its own.

func (Date) MarshalText

func (d Date) MarshalText() ([]byte, error)

func (Date) String

func (d Date) String() string

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(b []byte) error

UnmarshalJSON leaves d unchanged on null, like encoding/json does for other types.

func (*Date) UnmarshalText

func (d *Date) UnmarshalText(b []byte) error

type Email

type Email string

Email holds an email address. Decoding accepts any string; Validate checks it.

func (Email) Validate

func (e Email) Validate() error

Validate accepts a bare address only: "a@example.com", not "A <a@example.com>".

type Encoding

type Encoding map[string]PropertyEncoding

Encoding is how a form body writes each property, by name, as its encoding object says.

type File

type File struct {
	// contains filtered or unexported fields
}

File is binary content from bytes, a reader or a multipart form. A reader can be read once.

func DecodeFile

func DecodeFile(r *http.Request, isRequired bool) (File, error)

DecodeFile hands the body of r to a File that streams it, under the request's media type and with its content length as the size. It reads one byte ahead to tell an empty body.

func NewFile

func NewFile(data []byte, name, contentType string) File

func NewFileFromMultipart

func NewFileFromMultipart(h *multipart.FileHeader) File

func NewFileReader

func NewFileReader(r io.Reader, name, contentType string, size int64) File

NewFileReader wraps r; size is -1 when unknown.

func (File) Bytes

func (f File) Bytes() ([]byte, error)

func (File) ContentType

func (f File) ContentType() string

func (File) MarshalJSON

func (f File) MarshalJSON() ([]byte, error)

MarshalJSON writes the content as base64, like encoding/json does for []byte.

func (File) Name

func (f File) Name() string

func (File) Reader

func (f File) Reader() (io.ReadCloser, error)

func (File) Size

func (f File) Size() int64

Size is -1 when a reader was given without one.

func (*File) UnmarshalJSON

func (f *File) UnmarshalJSON(b []byte) error

type FormUnmarshaler

type FormUnmarshaler interface {
	UnmarshalForm(form *multipart.Form) error
}

FormUnmarshaler is a type that reads a form itself, as a generated union in a form body does.

type Kind

type Kind uint8

Kind is a set of JSON value kinds. A union variant lists the kinds it takes; a value has one.

const (
	KindNull Kind = 1 << iota
	KindBool
	// KindInteger is a number without a fraction or exponent.
	KindInteger
	KindNumber
	KindString
	KindArray
	KindObject

	KindAny = KindNull | KindBool | KindInteger | KindNumber | KindString | KindArray | KindObject
)

func (Kind) String

func (k Kind) String() string

type Nullable

type Nullable[T any] struct {
	// contains filtered or unexported fields
}

Nullable is a value that may be absent or null. Its zero value is absent.

func Null

func Null[T any]() Nullable[T]

Null returns a Nullable that is null.

func Some

func Some[T any](v T) Nullable[T]

Some returns a Nullable that holds v.

func (Nullable[T]) Get

func (n Nullable[T]) Get() (T, bool)

Get returns the value and true, or the zero value and false when it is absent or null.

func (Nullable[T]) IsNull

func (n Nullable[T]) IsNull() bool

IsNull reports whether it is null.

func (Nullable[T]) IsSet

func (n Nullable[T]) IsSet() bool

IsSet reports whether it holds a value or null.

func (Nullable[T]) IsZero

func (n Nullable[T]) IsZero() bool

IsZero reports whether it is absent, which omitzero leaves out.

func (Nullable[T]) MarshalJSON

func (n Nullable[T]) MarshalJSON() ([]byte, error)

MarshalJSON writes the value, or null when it holds none.

func (Nullable[T]) Or

func (n Nullable[T]) Or(def T) T

Or returns the value, or def when it is absent or null.

func (*Nullable[T]) UnmarshalJSON

func (n *Nullable[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a value, or null.

type Object

type Object struct {
	Name     string
	Props    []Prop
	Extra    *Prop
	IsClosed bool
}

Object is an object schema: its properties sorted by key, what other keys hold, and IsClosed.

type Param

type Param struct {
	Name       string
	Style      Style
	IsExplode  bool
	IsRequired bool
	IsJSON     bool
	IsReserved bool
	Default    string
}

Param describes one parameter: its name, how it is written, and whether it must be there. IsJSON is set for content application/json; Default is the JSON a decoder sets when it is not there. IsReserved is allowReserved: a query value or form cookie keeps the reserved characters.

type Presence

type Presence struct {
	IsChecked bool
	Objects   []Object
}

Presence holds the objects of request bodies, sorted by name; IsChecked adds checks to defaults.

func (Presence) Form

func (pr Presence) Form(body io.Reader, p Prop, enc Encoding) (io.Reader, error)

Form checks a url-encoded form against the object p names and returns the form to decode.

func (Presence) JSON

func (pr Presence) JSON(body io.Reader, p Prop) (io.Reader, error)

JSON checks a JSON body against p, sets the defaults it lacks and returns the body to decode.

func (Presence) Multipart

func (pr Presence) Multipart(r *http.Request, p Prop, maxMemory int64, enc Encoding) error

Multipart parses the multipart form of r, checks it against the object p names and fills it.

type PresenceChecker

type PresenceChecker interface {
	JSON(body io.Reader, p Prop) (io.Reader, error)
	Form(body io.Reader, p Prop, enc Encoding) (io.Reader, error)
	Multipart(r *http.Request, p Prop, maxMemory int64, enc Encoding) error
}

PresenceChecker checks which keys a request body has and fills its defaults before decoding.

type Prop

type Prop struct {
	Key        string
	IsRequired bool
	IsNullable bool
	Default    string
	Object     string
	Items      *Prop
	Values     *Prop
}

Prop is one value of a body: a property under its Key, a list item, a map value or the body.

type PropertyEncoding

type PropertyEncoding struct {
	ContentType string
	Style       Style
	IsExplode   bool
	IsReserved  bool
}

PropertyEncoding is a property written in ContentType, or as a query parameter of Style when set.

type Query

type Query map[string][]string

Query is the query of a request by key: each key unescaped, each value still percent-encoded, so a list is split at its commas before its items are unescaped.

func ParseQuery

func ParseQuery(raw string) Query

ParseQuery splits raw, the query of a request, at & into its keys. A key that does not unescape is left out; a value is unescaped when its parameter is decoded.

type Setter

type Setter interface {
	// contains filtered or unexported methods
}

Setter decodes a variant field from JSON or from a form.

func Into

func Into[T any](dst *T) Setter

Into returns the Setter of the variant field dst, which sets it only when the union picks it.

type Shape

type Shape struct {
	Required []string
	Known    []string
	IsClosed bool
}

Shape is one object a variant can be, with property names as Variant has them.

type Style

type Style string

Style is how a parameter is written, as OpenAPI names them.

const (
	StyleSimple         Style = "simple"
	StyleLabel          Style = "label"
	StyleMatrix         Style = "matrix"
	StyleForm           Style = "form"
	StyleSpaceDelimited Style = "spaceDelimited"
	StylePipeDelimited  Style = "pipeDelimited"
	StyleDeepObject     Style = "deepObject"
	StyleCookie         Style = "cookie"
)

type Union

type Union struct {
	IsAnyOf       bool
	Discriminator string
	IsLiteral     bool
	Shared        []string
	Variants      []Variant
	Also          []Union
}

Union describes a union to UnmarshalUnion. Shared are the property names the union holds next to its variants, which no variant counts as unknown. Also are more unions the value is at once. IsLiteral says the discriminator values are JSON booleans or numbers, not strings.

type Variant

type Variant struct {
	Name      string
	Kind      Kind
	Values    []string
	IsDefault bool
	IsAbsent  bool
	Required  []string
	Known     []string
	IsClosed  bool
	Shapes    []Shape
	Into      Setter
}

Variant describes one member of a union to UnmarshalUnion: the JSON kinds it takes, the discriminator values that pick it, and for objects its property names (Known nil takes any key). IsDefault picks it for a value no variant lists, IsAbsent for an object without the property. A member that is itself a union lists the objects it can be in Shapes and ranks by the best one.

Directories

Path Synopsis
Package httpclient builds and sends the requests of a generated client and reads its responses.
Package httpclient builds and sends the requests of a generated client and reads its responses.
Package httpserver holds the errors, error handlers, operation middleware and response writing of a generated server.
Package httpserver holds the errors, error handlers, operation middleware and response writing of a generated server.
Package mask hides sensitive values, for logs and other output.
Package mask hides sensitive values, for logs and other output.
Package mcptool holds what generated MCP tools call: their input, result and error.
Package mcptool holds what generated MCP tools call: their input, result and error.
Package validation checks values against the constraints of a spec and collects what fails.
Package validation checks values against the constraints of a spec and collects what fails.

Jump to

Keyboard shortcuts

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