runtime

package module
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: Apache-2.0 Imports: 23 Imported by: 22,035

README

runtime

Tests Coverage CI vuln scan CodeQL

Release Go Report Card CodeFactor Grade License

Doc GoDoc Discord Channel go version Top language Commits since latest release

A runtime for go OpenAPI toolkit.

The runtime component for use in code generation or as untyped usage.

Announcements

Complete documentation as github pages

Changes to the API surface in v0.30.0:

  • utility package header has now moved to github.com/go-openapi/runtime/server-middleware/negotiate/header

A shim is provided to support existing programs, with a deprecation notice.

Changes in semantics in v0.30.0:

Function negotiate.NegotiateContentType (available as an alias for backward compatibility as middleware.NegotiateContentType now performs a full match considering MIME parameters.

The previous behavior (matching in order of appearance after stripping parameters) may be enabled explicitly with option negotiate.WithIgnoreParameters.

  • 2026-05-07 : exposed UI and Spec middleware as a separate, dependency-free module.

Newly available package: github.com/go-openapi/runtime/server-middleware/docui that now holds our UI and spec serve middleware.

A shim is available in github.com/go-openapi/runtime/middleware to bridge the older UI options to the new ones, with a deprecation notice.

Methods that were unduly exported and purely used to manipulate options (e.g. SwaggerUIOpts.EnsureDefaults) have been removed. New options in docui should be used instead.

Users may reuse this middleware to serve a Redoc, Rapidoc or SwaggerUI documentation without importing the complete go-openapi scaffolding.

  • 2026-05-05 : exposed content negotiation methods as a separate, dependency-free module

Users may reuse these utilities to support content-negotiation without extra dependencies.

Newly available module: github.com/go-openapi/runtime/server-middleware

Newly available packages: github.com/go-openapi/runtime/server-middleware/negotiate and github.com/go-openapi/runtime/server-middleware/mediatype.

Status

API is stable.

Import this library in your project

go get github.com/go-openapi/runtime

Change log

See https://github.com/go-openapi/runtime/releases

For v0.29.0 release see release notes. From that release onwards, changes are tracked in the github release notes.

What coming next?

Moving forward, we want to :

  • fix a few known issues with some file upload requests (e.g. #286)
  • [] continue narrowing down the scope of dependencies:
    • split middleware and other useful utilities as a separate dependency-free module
    • yaml support in an independent module (v2)
    • introduce more up-to-date support for opentelemetry as a separate module that evolves independently from the main package (to avoid breaking changes, the existing API will remain maintained, but evolve at a slower pace than opentelemetry). (v2)
  • [] publish proper documentation and examples

Licensing

This library ships under the SPDX-License-Identifier: Apache-2.0.

See the license NOTICE, which recalls the licensing terms of all the pieces of software on top of which it has been built.

Other documentation

Cutting a new release

Maintainers can cut a new release by either:

  • running this workflow
  • or pushing a semver tag
    • signed tags are preferred
    • The tag message is prepended to release notes

Documentation

Overview

Package runtime exposes runtime client and server components for go-openapi toolkit.

Index

Constants

View Source
const (
	// HeaderContentType represents a [http] content-type header, it's value is supposed to be a mime type.
	HeaderContentType = "Content-Type"

	// HeaderTransferEncoding represents a [http] transfer-encoding header.
	HeaderTransferEncoding = "Transfer-Encoding"

	// HeaderAccept the Accept header.
	HeaderAccept = "Accept"
	// HeaderAuthorization the Authorization header.
	HeaderAuthorization = "Authorization"

	// DefaultMime the default fallback mime type.
	DefaultMime = "application/octet-stream"
	// JSONMime the json mime type.
	JSONMime = "application/json"
	// YAMLMime the [yaml] mime type. Set to the canonical RFC 9512
	// name (application/yaml). Legacy forms application/x-yaml,
	// text/yaml, and text/x-yaml — per RFC 9512 §2.1 "Deprecated
	// alias names for this type" — resolve to the same codec via
	// the mediatype alias bridge.
	YAMLMime = "application/yaml"
	// XMLMime the [xml] mime type.
	XMLMime = "application/xml"
	// TextMime the text mime type.
	TextMime = "text/plain"
	// HTMLMime the html mime type.
	HTMLMime = "text/html"
	// CSVMime the [csv] mime type.
	CSVMime = "text/csv"
	// MultipartFormMime the multipart form mime type.
	MultipartFormMime = "multipart/form-data"
	// URLencodedFormMime is the [url] encoded form mime type.
	URLencodedFormMime = "application/x-www-form-urlencoded"
)
View Source
const DefaultMaxUploadBodySize = int64(32) << 20

DefaultMaxUploadBodySize limits the size of the body to upload forms to 32MB.

Use an explicit BindFormMaxBody option to change this limit.

View Source
const DefaultMaxUploadFilenameLength = 1024

DefaultMaxUploadFilenameLength is the default cap applied to FileHeader.Filename for each declared file when BindForm is invoked without an explicit BindFormMaxFilenameLen option.

Multipart headers are allocated per part; an attacker submitting multi-MB filenames inflates the parser's memory footprint. 1 KiB matches the IETF guidance for sane filename length and is enough for realistic uploads.

Variables

View Source
var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ any) error { return nil })

DiscardConsumer does absolutely nothing, it's a black hole.

View Source
var DiscardProducer = ProducerFunc(func(_ io.Writer, _ any) error { return nil })

DiscardProducer does absolutely nothing, it's a black hole.

View Source
var Statuses = map[int]string{
	100: "Continue",
	101: "Switching Protocols",
	102: "Processing",
	103: "Checkpoint",
	122: "URI too long",
	200: "OK",
	201: "Created",
	202: "Accepted",
	203: "Request Processed",
	204: "No Content",
	205: "Reset Content",
	206: "Partial Content",
	207: "Multi-Status",
	208: "Already Reported",
	226: "IM Used",
	300: "Multiple Choices",
	301: "Moved Permanently",
	302: "Found",
	303: "See Other",
	304: "Not Modified",
	305: "Use Proxy",
	306: "Switch Proxy",
	307: "Temporary Redirect",
	308: "Permanent Redirect",
	400: "Bad Request",
	401: "Unauthorized",
	402: "Payment Required",
	403: "Forbidden",
	404: "Not Found",
	405: "Method Not Allowed",
	406: "Not Acceptable",
	407: "Proxy Authentication Required",
	408: "Request Timeout",
	409: "Conflict",
	410: "Gone",
	411: "Length Required",
	412: "Precondition Failed",
	413: "Request Entity Too Large",
	414: "Request-URI Too Long",
	415: "Unsupported Media Type",
	416: "Request Range Not Satisfiable",
	417: "Expectation Failed",
	418: "I'm a teapot",
	420: "Enhance Your Calm",
	422: "Unprocessable Entity",
	423: "Locked",
	424: "Failed Dependency",
	426: "Upgrade Required",
	428: "Precondition Required",
	429: "Too Many Requests",
	431: "Request Header Fields Too Large",
	444: "No Response",
	449: "Retry With",
	450: "Blocked by Windows Parental Controls",
	451: "Unavailable For Legal Reasons",
	499: "Client Closed Request",
	500: "Internal Server Error",
	501: "Not Implemented",
	502: "Bad Gateway",
	503: "Service Unavailable",
	504: "Gateway Timeout",
	505: "HTTP Version Not Supported",
	506: "Variant Also Negotiates",
	507: "Insufficient Storage",
	508: "Loop Detected",
	509: "Bandwidth Limit Exceeded",
	510: "Not Extended",
	511: "Network Authentication Required",
	598: "Network read timeout error",
	599: "Network connect timeout error",
}

Statuses lists the most common HTTP status codes to default message. taken from https://httpstatuses.com/

Functions

func AllowsBody

func AllowsBody(r *http.Request) bool

AllowsBody returns true if the request allows for a body.

func BindForm added in v0.31.0

func BindForm(r *http.Request, opts ...BindOption) (fatal bool, err error)

BindForm parses r as multipart/form-data, falling back to application/x-www-form-urlencoded when the request is not multipart. On success, r.MultipartForm and r.PostForm are populated; the caller can read non-file form values via Values(r.Form) after the call returns.

All errors produced by BindForm itself (parse failure, missing required field, cap exceeded) are *errors.ParseError values built via errors.NewParseError, matching the untyped middleware/parameter.go path. Errors returned by per-file binders flow through verbatim — binders own their HTTP-aware error shape.

Per-file binders declared via BindFormFile run in declaration order after a successful parse. Their errors are accumulated and returned wrapped in errors.CompositeValidationError; the caller typically appends the returned err to its own []error and continues with non-file parameter binding.

Return semantics:

  • fatal=true, err!=nil: parse failure or a hard cap (e.g. BindFormMaxFiles) was exceeded. No per-file binders ran; the caller MUST return err immediately.
  • fatal=false, err!=nil: one or more per-file binders produced errors. The form parsed successfully; r.Form is populated. The caller appends err to its accumulator and continues.
  • fatal=false, err==nil: full success.

fatal==true implies err!=nil.

Defaults applied out of the box:

Caller responsibilities the helper does NOT cover:

  • Set http.Server.ReadTimeout / http.Server.IdleTimeout to defend against slow-read attacks.
  • Decompress Content-Encoding: gzip request bodies upstream if the API accepts them, using a size-limited reader.
  • Treat FileHeader.Filename as untrusted user input; never use it directly as a filesystem path.

func CanHaveBody

func CanHaveBody(method string) bool

CanHaveBody returns true if this method can have a body.

func ClosesStream

func ClosesStream(opts *byteStreamOpts)

ClosesStream when the bytestream consumer or producer is finished.

func ContentType

func ContentType(headers http.Header) (string, string, error)

ContentType parses a content type header.

func FormFile added in v0.32.0

func FormFile(r *http.Request, name string) (multipart.File, *multipart.FileHeader, error)

FormFile resolves a file field from a parsed form body, transparently handling both content types accepted for `type: file` parameters by the OpenAPI 2.0 spec:

  • multipart/form-data — delegates to http.Request.FormFile.
  • application/x-www-form-urlencoded — looks up the field in r.PostForm and synthesizes a multipart.File backed by the value bytes plus a multipart.FileHeader with Filename equal to the field name and Size set to the byte length.

Returns http.ErrMissingFile when the field is absent under either content type. Callers must have parsed the body upstream (e.g. via BindForm or http.Request.ParseForm) before reading from the urlencoded path — http.Request.FormFile takes care of parsing on the multipart path.

Presence is the only criterion for binding a urlencoded file: an empty value (e.g. `file=`) is bound as a zero-byte file.

func HasBody

func HasBody(r *http.Request) bool

HasBody returns true if this method needs a content-type.

func IsSafe

func IsSafe(r *http.Request) bool

IsSafe returns true if this is a request with a safe method.

func JSONRequest

func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error)

JSONRequest creates a new http request with json headers set.

It uses context.Background.

func ReadCollectionValue

func ReadCollectionValue(values Gettable, name, collectionFormat string) []string

ReadCollectionValue reads a collection value from a string data source.

func ReadSingleValue

func ReadSingleValue(values Gettable, name string) string

ReadSingleValue reads a single value from the source.

func ValidateFilenameLength added in v0.31.0

func ValidateFilenameLength(paramName, paramIn, filename string, maxLen int) error

ValidateFilenameLength enforces the FileHeader.Filename length cap that BindForm applies via BindFormFile declarations. Untyped binder paths that fetch the file via http.Request.FormFile directly (rather than declaring the file through BindFormFile) call this to opt into the same protection.

Returns nil if filename length is within maxLen or maxLen <= 0. Otherwise returns a *errors.ParseError suitable for direct return from a parameter binder. The error embeds a truncated preview of the offending filename to keep the error message bounded.

Types

type APIError

type APIError struct {
	OperationName string
	Response      any
	Code          int
}

APIError wraps an error model and captures the status code.

func NewAPIError

func NewAPIError(opName string, payload any, code int) *APIError

NewAPIError creates a new API error.

func (*APIError) Error

func (o *APIError) Error() string

func (*APIError) IsClientError added in v0.23.0

func (o *APIError) IsClientError() bool

IsClientError returns true when this API response returns a 4xx status code.

func (*APIError) IsCode added in v0.23.0

func (o *APIError) IsCode(code int) bool

IsCode returns true when this API response returns a given status code.

func (*APIError) IsRedirect added in v0.23.0

func (o *APIError) IsRedirect() bool

IsRedirect returns true when this API response returns a 3xx status code.

func (*APIError) IsServerError added in v0.23.0

func (o *APIError) IsServerError() bool

IsServerError returns true when this API response returns a 5xx status code.

func (*APIError) IsSuccess added in v0.23.0

func (o *APIError) IsSuccess() bool

IsSuccess returns true when this API response returns a 2xx status code.

func (*APIError) String

func (o *APIError) String() string

type Authenticator

type Authenticator interface {
	Authenticate(any) (bool, any, error)
}

Authenticator represents an authentication strategy implementations of Authenticator know how to authenticate the request data and translate that into a valid principal object or an error.

type AuthenticatorFunc

type AuthenticatorFunc func(any) (bool, any, error)

AuthenticatorFunc turns a function into an authenticator.

func (AuthenticatorFunc) Authenticate

func (f AuthenticatorFunc) Authenticate(params any) (bool, any, error)

Authenticate authenticates the request with the provided data.

type Authorizer

type Authorizer interface {
	Authorize(*http.Request, any) error
}

Authorizer represents an authorization strategy implementations of Authorizer know how to authorize the principal object using the request data and returns error if unauthorized.

type AuthorizerFunc

type AuthorizerFunc func(*http.Request, any) error

AuthorizerFunc turns a function into an authorizer.

func (AuthorizerFunc) Authorize

func (f AuthorizerFunc) Authorize(r *http.Request, principal any) error

Authorize authorizes the processing of the request for the principal.

type BindOption added in v0.31.0

type BindOption func(*bindConfig)

BindOption configures BindForm. The variadic style keeps simple call sites simple and lets new knobs (security caps, additional behaviour) be added without breaking the signature.

func BindFormFile added in v0.31.0

func BindFormFile(name string, required bool, bind FileBinder) BindOption

BindFormFile declares a file field to bind under the given form name. If required is true and the field is absent, BindForm produces the per-field error.

errors.NewParseError(name, "formData", "", http.ErrMissingFile)

If required is false, absence is silent (no error, no bind).

The bind callback runs only when the field is present. It is the site where both validation and assignment happen — see FileBinder.

FileHeader.Filename is attacker-controlled text; the binder MUST NOT use it directly as a filesystem path. The helper does not touch the filesystem.

func BindFormMaxBody added in v0.31.0

func BindFormMaxBody(n int64) BindOption

BindFormMaxBody caps the size of the body read from a http form before parsing.

The limit is set to 32MB by default. This default limit is applied for any n=0.

The limit is disabled for n<0, assuming the caller has already capped the body size upstream.

func BindFormMaxFilenameLen added in v0.31.0

func BindFormMaxFilenameLen(n int) BindOption

BindFormMaxFilenameLen rejects per-file headers whose Filename length exceeds n. 0 means no cap; the default applied when this option is not supplied is DefaultMaxUploadFilenameLength. The cap is a per-field bind error (non-fatal); other declared files still run.

func BindFormMaxFiles added in v0.31.0

func BindFormMaxFiles(n int) BindOption

BindFormMaxFiles rejects parses where the total number of file parts across all field names exceeds n. 0 (the default) means no cap. Exceeding the cap is a fatal error — BindForm returns fatal=true and no per-file binders run.

func BindFormMaxParseMemory added in v0.31.0

func BindFormMaxParseMemory(n int64) BindOption

BindFormMaxParseMemory caps the in-memory portion of a multipart body. Bytes beyond this are spilled to temporary files on disk by the stdlib parser. 0 (the default) defers to the stdlib's 32 MB.

This option does NOT cap total body bytes — see BindFormMaxBody for that. The default body cap (DefaultMaxUploadBodySize = 32 MB) is applied even when this option is not supplied, so out of the box BindForm is bounded; callers with stricter or looser requirements adjust via BindFormMaxBody.

type CSVOpt added in v0.27.0

type CSVOpt func(*csvOpts)

CSVOpt alter the behavior of the CSV consumer or producer.

func WithCSVClosesStream added in v0.27.0

func WithCSVClosesStream() CSVOpt

func WithCSVReaderOpts added in v0.27.0

func WithCSVReaderOpts(reader csv.Reader) CSVOpt

WithCSVReaderOpts specifies the options to csv.Reader when reading CSV.

func WithCSVSkipLines added in v0.27.0

func WithCSVSkipLines(skipped int) CSVOpt

WithCSVSkipLines will skip header lines.

func WithCSVWriterOpts added in v0.27.0

func WithCSVWriterOpts(writer csv.Writer) CSVOpt

WithCSVWriterOpts specifies the options to csv.Writer when writing CSV.

type CSVReader added in v0.27.0

type CSVReader interface {
	Read() ([]string, error)
}

type CSVWriter added in v0.27.0

type CSVWriter interface {
	Write([]string) error
	Flush()
	Error() error
}

type ClientAuthInfoWriter

type ClientAuthInfoWriter interface {
	AuthenticateRequest(ClientRequest, strfmt.Registry) error
}

A ClientAuthInfoWriter implementor knows how to write authentication info to a request.

type ClientAuthInfoWriterFunc

type ClientAuthInfoWriterFunc func(ClientRequest, strfmt.Registry) error

A ClientAuthInfoWriterFunc converts a function to a request writer interface.

func (ClientAuthInfoWriterFunc) AuthenticateRequest

func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error

AuthenticateRequest adds authentication data to the request.

type ClientOperation

type ClientOperation struct {
	ID                 string
	Method             string
	PathPattern        string
	ProducesMediaTypes []string
	ConsumesMediaTypes []string
	Schemes            []string
	AuthInfo           ClientAuthInfoWriter
	Params             ClientRequestWriter
	Reader             ClientResponseReader
	Context            context.Context //nolint:containedctx // we precisely want this type to contain the request context
	Client             *http.Client
}

ClientOperation represents the context for a swagger operation to be submitted to the transport.

type ClientRequest

type ClientRequest interface {
	SetHeaderParam(string, ...string) error

	GetHeaderParams() http.Header

	SetQueryParam(string, ...string) error

	SetFormParam(string, ...string) error

	SetPathParam(string, string) error

	GetQueryParams() url.Values

	SetFileParam(string, ...NamedReadCloser) error

	SetBodyParam(any) error

	SetTimeout(time.Duration) error

	GetMethod() string

	GetPath() string

	GetBody() []byte

	GetBodyParam() any

	GetFileParam() map[string][]NamedReadCloser
}

ClientRequest is an interface for things that know how to add information to a swagger client request.

type ClientRequestWriter

type ClientRequestWriter interface {
	WriteToRequest(ClientRequest, strfmt.Registry) error
}

ClientRequestWriter is an interface for things that know how to write to a request.

type ClientRequestWriterFunc

type ClientRequestWriterFunc func(ClientRequest, strfmt.Registry) error

ClientRequestWriterFunc converts a function to a request writer interface.

func (ClientRequestWriterFunc) WriteToRequest

func (fn ClientRequestWriterFunc) WriteToRequest(req ClientRequest, reg strfmt.Registry) error

WriteToRequest adds data to the request.

type ClientResponse

type ClientResponse interface {
	Code() int
	Message() string
	GetHeader(string) string
	GetHeaders(string) []string
	Body() io.ReadCloser
}

A ClientResponse represents a client response.

This bridges between responses obtained from different transports.

type ClientResponseReader

type ClientResponseReader interface {
	ReadResponse(ClientResponse, Consumer) (any, error)
}

A ClientResponseReader is an interface for things want to read a response. An application of this is to create structs from response values.

type ClientResponseReaderFunc

type ClientResponseReaderFunc func(ClientResponse, Consumer) (any, error)

A ClientResponseReaderFunc turns a function into a ClientResponseReader interface implementation.

func (ClientResponseReaderFunc) ReadResponse

func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (any, error)

ReadResponse reads the response.

type ClientResponseStatus added in v0.23.0

type ClientResponseStatus interface {
	IsSuccess() bool
	IsRedirect() bool
	IsClientError() bool
	IsServerError() bool
	IsCode(int) bool
}

A ClientResponseStatus is a common interface implemented by all responses on the generated code You can use this to treat any client response based on status code.

type ClientTransport

type ClientTransport interface {
	// Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error)
	Submit(*ClientOperation) (any, error)
}

A ClientTransport implementor knows how to submit Request objects to some destination.

type Consumer

type Consumer interface {
	// Consume performs the binding of request values
	Consume(io.Reader, any) error
}

Consumer implementations know how to bind the values on the provided interface to data provided by the request body.

func ByteStreamConsumer

func ByteStreamConsumer(opts ...byteStreamOpt) Consumer

ByteStreamConsumer creates a consumer for byte streams.

The consumer consumes from a provided reader into the data passed by reference.

Supported output underlying types and interfaces, prioritized in this order:

func CSVConsumer

func CSVConsumer(opts ...CSVOpt) Consumer

CSVConsumer creates a new CSV consumer.

The consumer consumes CSV records from a provided reader into the data passed by reference.

CSVOpts options may be specified to alter the default CSV behavior on the reader and the writer side (e.g. separator, skip header, ...). The defaults are those of the standard library's csv.Reader and csv.Writer.

Supported output underlying types and interfaces, prioritized in this order:

The consumer prioritizes situations where buffering the input is not required.

func JSONConsumer

func JSONConsumer() Consumer

JSONConsumer creates a new JSON consumer.

func TextConsumer

func TextConsumer() Consumer

TextConsumer creates a new text consumer.

func XMLConsumer

func XMLConsumer() Consumer

XMLConsumer creates a new XML consumer.

type ConsumerFunc

type ConsumerFunc func(io.Reader, any) error

ConsumerFunc represents a function that can be used as a consumer.

func (ConsumerFunc) Consume

func (fn ConsumerFunc) Consume(reader io.Reader, data any) error

Consume consumes the reader into the data parameter.

type ContentTyper added in v0.30.0

type ContentTyper interface {
	ContentType() string
}

ContentTyper is implemented by values that declare their own MIME content type. The client runtime consults it in two places:

  • on a body payload set via [SetBodyParam]: when the payload is a stream (io.Reader, io.ReadCloser) and ContentType returns a non-empty value, that value becomes the wire Content-Type header instead of the operation's picked consumes entry.

  • on individual file values inside a multipart upload: their per- part Content-Type header is taken from ContentType() rather than sniffed via http.DetectContentType.

An empty string return is treated as "no opinion" and the runtime falls back to its default selection. Values that have no content type to declare may simply not implement the interface.

See docs/MEDIA_TYPES.md for the full client-side selection algorithm.

type ContextValidatable added in v0.19.22

type ContextValidatable interface {
	ContextValidate(context.Context, strfmt.Registry) error
}

ContextValidatable types implementing this interface allow customizing their validation this will be used instead of the reflective validation based on the spec document. the implementations are assumed to have been generated by the swagger tool so they should contain all the context validations obtained from the spec.

type File

type File = fileutils.File

File represents an uploaded file. Re-exported from fileutils.File for backwards compatibility.

See BindForm (in form.go) for the orchestrator that parses multipart / urlencoded request bodies and binds declared file fields onto handler-side targets.

type FileBinder added in v0.31.0

type FileBinder func(file multipart.File, header *multipart.FileHeader) error

FileBinder is the per-file callback invoked by BindForm when a declared file field is present.

The callback is responsible for BOTH validating the file (size, MIME, etc.) AND assigning the bound file to its destination — typically using:

o.FieldName = &runtime.File{Data: file, Header: header}

Returning a non-nil error surfaces the error in BindForm's per-field accumulator. Errors from the binder flow through verbatim — the binder is expected to produce HTTP-aware errors (e.g. errors.ExceedsMaximum from go-openapi/validate).

type Gettable

type Gettable interface {
	GetOK(string) ([]string, bool, bool)
}

Gettable for things with a method [GetOK](string) (data string, hasKey bool, hasValue bool).

type NamedReadCloser

type NamedReadCloser interface {
	io.ReadCloser
	Name() string
}

NamedReadCloser represents a named ReadCloser interface.

func NamedReader

func NamedReader(name string, rdr io.Reader) NamedReadCloser

NamedReader creates a NamedReadCloser for use as file upload.

type OperationHandler

type OperationHandler interface {
	Handle(any) (any, error)
}

OperationHandler a handler for a swagger operation.

type OperationHandlerFunc

type OperationHandlerFunc func(any) (any, error)

OperationHandlerFunc an adapter for a function to the OperationHandler interface.

func (OperationHandlerFunc) Handle

func (s OperationHandlerFunc) Handle(data any) (any, error)

Handle implements the operation handler interface.

type Producer

type Producer interface {
	// Produce writes to the http response
	Produce(io.Writer, any) error
}

Producer implementations know how to turn the provided interface into a valid HTTP response.

func ByteStreamProducer

func ByteStreamProducer(opts ...byteStreamOpt) Producer

ByteStreamProducer creates a producer for byte streams.

The producer takes input data then writes to an output writer (essentially as a pipe).

Supported input underlying types and interfaces, prioritized in this order:

func CSVProducer

func CSVProducer(opts ...CSVOpt) Producer

CSVProducer creates a new CSV producer.

The producer takes input data then writes as CSV to an output writer (essentially as a pipe).

Supported input underlying types and interfaces, prioritized in this order:

The producer prioritizes situations where buffering the input is not required.

func JSONProducer

func JSONProducer() Producer

JSONProducer creates a new JSON producer.

func TextProducer

func TextProducer() Producer

TextProducer creates a new text producer.

func XMLProducer

func XMLProducer() Producer

XMLProducer creates a new XML producer.

type ProducerFunc

type ProducerFunc func(io.Writer, any) error

ProducerFunc represents a function that can be used as a producer.

func (ProducerFunc) Produce

func (f ProducerFunc) Produce(writer io.Writer, data any) error

Produce produces the response for the provided data.

type TestClientRequest added in v0.19.25

type TestClientRequest struct {
	Headers http.Header
	Body    any
}

func (*TestClientRequest) GetBody added in v0.19.25

func (t *TestClientRequest) GetBody() []byte

func (*TestClientRequest) GetBodyParam added in v0.19.25

func (t *TestClientRequest) GetBodyParam() any

func (*TestClientRequest) GetFileParam added in v0.19.25

func (t *TestClientRequest) GetFileParam() map[string][]NamedReadCloser

func (*TestClientRequest) GetHeaderParams added in v0.19.25

func (t *TestClientRequest) GetHeaderParams() http.Header

func (*TestClientRequest) GetMethod added in v0.19.25

func (t *TestClientRequest) GetMethod() string

func (*TestClientRequest) GetPath added in v0.19.25

func (t *TestClientRequest) GetPath() string

func (*TestClientRequest) GetQueryParams added in v0.19.25

func (t *TestClientRequest) GetQueryParams() url.Values

func (*TestClientRequest) SetBodyParam added in v0.19.25

func (t *TestClientRequest) SetBodyParam(body any) error

func (*TestClientRequest) SetFileParam added in v0.19.25

func (t *TestClientRequest) SetFileParam(_ string, _ ...NamedReadCloser) error

func (*TestClientRequest) SetFormParam added in v0.19.25

func (t *TestClientRequest) SetFormParam(_ string, _ ...string) error

func (*TestClientRequest) SetHeaderParam added in v0.19.25

func (t *TestClientRequest) SetHeaderParam(name string, values ...string) error

func (*TestClientRequest) SetPathParam added in v0.19.25

func (t *TestClientRequest) SetPathParam(_ string, _ string) error

func (*TestClientRequest) SetQueryParam added in v0.19.25

func (t *TestClientRequest) SetQueryParam(_ string, _ ...string) error

func (*TestClientRequest) SetTimeout added in v0.19.25

func (t *TestClientRequest) SetTimeout(time.Duration) error

type Validatable

type Validatable interface {
	Validate(strfmt.Registry) error
}

Validatable types implementing this interface allow customizing their validation this will be used instead of the reflective validation based on the spec document. the implementations are assumed to have been generated by the swagger tool so they should contain all the validations obtained from the spec.

type Values

type Values map[string][]string

Values typically represent parameters on a http request.

func (Values) GetOK

func (v Values) GetOK(key string) (value []string, hasKey bool, hasValue bool)

GetOK returns the values collection for the given key. When the key is present in the map it will return true for hasKey. When the value is not empty it will return true for hasValue.

Directories

Path Synopsis
client-middleware
opentracing module
internal
Package middleware provides the library with helper functions for serving swagger APIs.
Package middleware provides the library with helper functions for serving swagger APIs.
denco
Package denco provides fast URL router.
Package denco provides fast URL router.
header
Package header forwards to the relocated implementation at github.com/go-openapi/runtime/server-middleware/negotiate/header.
Package header forwards to the relocated implementation at github.com/go-openapi/runtime/server-middleware/negotiate/header.

Jump to

Keyboard shortcuts

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