core

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MPL-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package core defines the foundational types and interfaces for the neoma REST API framework, including the API configuration, HTTP context, JSON Schema, OpenAPI specification, operation registration, content negotiation, error handling, and middleware.

Index

Constants

View Source
const (
	OpenAPIVersion30 = "3.0.3"
	OpenAPIVersion31 = "3.1.0"
	OpenAPIVersion32 = "3.2.0"
)

Supported OpenAPI specification versions.

View Source
const (
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeArray   = "array"
	TypeObject  = "object"
)

JSON Schema type constants as defined in the JSON Schema Validation specification (RFC draft-bhutton-json-schema-validation).

Variables

View Source
var (
	// MsgUnexpectedProperty is used when an object contains a property not
	// defined in the schema.
	MsgUnexpectedProperty = "unexpected property"

	// MsgExpectedRFC3339DateTime is used when a string is not a valid
	// RFC 3339 date-time.
	MsgExpectedRFC3339DateTime = "expected string to be RFC 3339 date-time"

	// MsgExpectedRFC1123DateTime is used when a string is not a valid
	// RFC 1123 date-time.
	MsgExpectedRFC1123DateTime = "expected string to be RFC 1123 date-time"

	// MsgExpectedRFC3339Date is used when a string is not a valid RFC 3339
	// date.
	MsgExpectedRFC3339Date = "expected string to be RFC 3339 date"

	// MsgExpectedRFC3339Time is used when a string is not a valid RFC 3339
	// time.
	MsgExpectedRFC3339Time = "expected string to be RFC 3339 time"

	// MsgExpectedRFC5322Email is used when a string is not a valid RFC 5322
	// email address.
	MsgExpectedRFC5322Email = "expected string to be RFC 5322 email: %v"

	// MsgExpectedRFC5890Hostname is used when a string is not a valid
	// RFC 5890 hostname.
	MsgExpectedRFC5890Hostname = "expected string to be RFC 5890 hostname"

	// MsgExpectedRFC2673IPv4 is used when a string is not a valid RFC 2673
	// IPv4 address.
	MsgExpectedRFC2673IPv4 = "expected string to be RFC 2673 ipv4"

	// MsgExpectedRFC2373IPv6 is used when a string is not a valid RFC 2373
	// IPv6 address.
	MsgExpectedRFC2373IPv6 = "expected string to be RFC 2373 ipv6"

	// MsgExpectedRFCIPAddr is used when a string is not a valid IPv4 or
	// IPv6 address.
	MsgExpectedRFCIPAddr = "expected string to be either RFC 2673 ipv4 or RFC 2373 ipv6"

	// MsgExpectedRFC3986URI is used when a string is not a valid RFC 3986
	// URI.
	MsgExpectedRFC3986URI = "expected string to be RFC 3986 uri: %v"

	// MsgExpectedRFC4122UUID is used when a string is not a valid RFC 4122
	// UUID.
	MsgExpectedRFC4122UUID = "expected string to be RFC 4122 uuid: %v"

	// MsgExpectedRFC6570URITemplate is used when a string is not a valid
	// RFC 6570 URI template.
	MsgExpectedRFC6570URITemplate = "expected string to be RFC 6570 uri-template"

	// MsgExpectedRFC6901JSONPointer is used when a string is not a valid
	// RFC 6901 JSON pointer.
	MsgExpectedRFC6901JSONPointer = "expected string to be RFC 6901 json-pointer"

	// MsgExpectedRFC6901RelativeJSONPointer is used when a string is not a
	// valid RFC 6901 relative JSON pointer.
	MsgExpectedRFC6901RelativeJSONPointer = "expected string to be RFC 6901 relative-json-pointer"

	// MsgExpectedRegexp is used when a string is not a valid regular
	// expression.
	MsgExpectedRegexp = "expected string to be regex: %v"

	// MsgExpectedMatchAtLeastOneSchema is used when a value does not match
	// any schema in an anyOf constraint.
	MsgExpectedMatchAtLeastOneSchema = "expected value to match at least one schema but matched none"

	// MsgExpectedMatchExactlyOneSchema is used when a value does not match
	// exactly one schema in a oneOf constraint.
	MsgExpectedMatchExactlyOneSchema = "expected value to match exactly one schema but matched none"

	// MsgExpectedNotMatchSchema is used when a value matches a schema it
	// should not (not constraint).
	MsgExpectedNotMatchSchema = "expected value to not match schema"

	// MsgExpectedPropertyNameInObject is used when a propertyNames schema
	// value is not present in the object.
	MsgExpectedPropertyNameInObject = "expected propertyName value to be present in object"

	// MsgExpectedBoolean is used when a value is not a boolean.
	MsgExpectedBoolean = "expected boolean"

	// MsgExpectedDuration is used when a string is not a valid duration.
	MsgExpectedDuration = "expected duration: %v"

	// MsgExpectedNumber is used when a value is not a number.
	MsgExpectedNumber = "expected number"

	// MsgExpectedInteger is used when a value is not an integer.
	MsgExpectedInteger = "expected integer"

	// MsgExpectedString is used when a value is not a string.
	MsgExpectedString = "expected string"

	// MsgExpectedBase64String is used when a string is not valid base64.
	MsgExpectedBase64String = "expected string to be base64 encoded"

	// MsgExpectedArray is used when a value is not an array.
	MsgExpectedArray = "expected array"

	// MsgExpectedObject is used when a value is not an object.
	MsgExpectedObject = "expected object"

	// MsgExpectedArrayItemsUnique is used when array items are not unique.
	MsgExpectedArrayItemsUnique = "expected array items to be unique"

	// MsgExpectedOneOf is used when a value is not one of the allowed enum
	// values.
	MsgExpectedOneOf = "expected value to be one of %s"

	// MsgExpectedMinimumNumber is used when a number is below the minimum.
	MsgExpectedMinimumNumber = "expected number >= %v"

	// MsgExpectedExclusiveMinimumNumber is used when a number is at or
	// below the exclusive minimum.
	MsgExpectedExclusiveMinimumNumber = "expected number > %v"

	// MsgExpectedMaximumNumber is used when a number exceeds the maximum.
	MsgExpectedMaximumNumber = "expected number <= %v"

	// MsgExpectedExclusiveMaximumNumber is used when a number is at or
	// above the exclusive maximum.
	MsgExpectedExclusiveMaximumNumber = "expected number < %v"

	// MsgExpectedNumberBeMultipleOf is used when a number is not a multiple
	// of the required value.
	MsgExpectedNumberBeMultipleOf = "expected number to be a multiple of %v"

	// MsgExpectedMinLength is used when a string is shorter than the
	// minimum length.
	MsgExpectedMinLength = "expected length >= %d"

	// MsgExpectedMaxLength is used when a string exceeds the maximum
	// length.
	MsgExpectedMaxLength = "expected length <= %d"

	// MsgExpectedBePattern is used when a string does not match the
	// expected named pattern.
	MsgExpectedBePattern = "expected string to be %s"

	// MsgExpectedMatchPattern is used when a string does not match the
	// required regex pattern.
	MsgExpectedMatchPattern = "expected string to match pattern %s"

	// MsgExpectedMinItems is used when an array has fewer items than the
	// minimum.
	MsgExpectedMinItems = "expected array length >= %d"

	// MsgExpectedMaxItems is used when an array has more items than the
	// maximum.
	MsgExpectedMaxItems = "expected array length <= %d"

	// MsgExpectedMinProperties is used when an object has fewer properties
	// than the minimum.
	MsgExpectedMinProperties = "expected object with >= %d properties"

	// MsgExpectedMaxProperties is used when an object has more properties
	// than the maximum.
	MsgExpectedMaxProperties = "expected object with <= %d properties"

	// MsgExpectedRequiredProperty is used when a required property is
	// missing from the object.
	MsgExpectedRequiredProperty = "expected required property %s to be present"

	// MsgExpectedDependentRequiredProperty is used when a conditionally
	// required property is missing.
	MsgExpectedDependentRequiredProperty = "expected property %s to be present when %s is present"
)

Validation error message templates. These package-level variables can be overridden to customize or localize the messages produced by schema validation. Templates containing %v or %s verbs are formatted with fmt.Sprintf at runtime.

View Source
var (
	// ErrUnknownContentType is returned when the request Content-Type header
	// specifies a media type that has no registered Format.
	ErrUnknownContentType = errors.New("unknown content type")

	// ErrUnknownAcceptContentType is returned when the request Accept header
	// specifies a media type that has no registered Format.
	ErrUnknownAcceptContentType = errors.New("unknown accept content type")
)
View Source
var ErrSchemaInvalid = errors.New("schema is invalid")

ErrSchemaInvalid is returned when a schema fails validation.

Functions

func BaseType

func BaseType(t reflect.Type) reflect.Type

BaseType returns the innermost element type after dereferencing pointers and unwrapping slices, arrays, and maps.

func Deref

func Deref(t reflect.Type) reflect.Type

Deref returns the underlying non-pointer type by repeatedly dereferencing pointer types.

func ErrorWithHeaders

func ErrorWithHeaders(err error, headers http.Header) error

ErrorWithHeaders wraps an error with additional HTTP headers that will be sent in the response. The returned error implements the Headerer interface.

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

IsEmptyValue reports whether v is the zero value for its type. It handles arrays, maps, slices, strings, booleans, numeric types, and pointer/interface types.

func IsNilValue

func IsNilValue(v any) bool

IsNilValue reports whether v is nil or a nillable type (chan, func, interface, map, pointer, slice) whose underlying value is nil.

func MarshalJSON

func MarshalJSON(fields []JSONFieldInfo, extensions map[string]any) ([]byte, error)

MarshalJSON marshals the given fields and extension properties into a JSON object. Each field's inclusion is governed by its OmitType. Extension entries are merged into the output, allowing OpenAPI specification extensions (x-* fields).

func SetReadDeadline

func SetReadDeadline(w http.ResponseWriter, deadline time.Time) error

SetReadDeadline sets a read deadline on the underlying connection of the given ResponseWriter, unwrapping middleware wrappers as needed. It returns http.ErrNotSupported if the writer does not support deadlines.

Types

type API

type API interface {
	Adapter() Adapter
	OpenAPI() *OpenAPI
	Negotiate(accept string) (string, error)
	Transform(ctx Context, status string, v any) (any, error)
	Marshal(w io.Writer, contentType string, v any) error
	Unmarshal(contentType string, data []byte, v any) error
	UseMiddleware(middlewares ...MiddlewareFunc)
	Middlewares() Middlewares
	ErrorHandler() ErrorHandler
	GenerateOperationID(method, path string) string
	UseGlobalMiddleware(middlewares ...MiddlewareFunc)
}

API is the primary interface for interacting with a running neoma API. It provides access to the underlying adapter, OpenAPI spec, content negotiation, marshaling, middleware registration, and error handling.

type Adapter

type Adapter interface {
	// Handle registers a handler for the given operation.
	Handle(op *Operation, handler func(ctx Context))

	// ServeHTTP dispatches incoming HTTP requests to registered handlers.
	ServeHTTP(http.ResponseWriter, *http.Request)
}

Adapter defines the interface between neoma and an HTTP router. An adapter registers operation handlers and serves HTTP requests. Every adapter package must also export these package-level symbols:

func NewAdapter(router) Adapter
func New(router, Config) API
func Unwrap(Context) <router-specific type>
var MultipartMaxMemory int64

Optional, when the router supports native route groups:

func NewAdapterWithGroup(router, group) Adapter

type Components

type Components struct {
	Schemas         Registry                        `yaml:"schemas,omitempty"`
	Responses       map[string]*Response            `yaml:"responses,omitempty"`
	Parameters      map[string]*Param               `yaml:"parameters,omitempty"`
	Examples        map[string]*Example             `yaml:"examples,omitempty"`
	RequestBodies   map[string]*RequestBody         `yaml:"requestBodies,omitempty"`
	Headers         map[string]*Header              `yaml:"headers,omitempty"`
	SecuritySchemes map[string]*SecurityScheme      `yaml:"securitySchemes,omitempty"`
	Links           map[string]*Link                `yaml:"links,omitempty"`
	Callbacks       map[string]map[string]*PathItem `yaml:"callbacks,omitempty"`
	Extensions      map[string]any                  `yaml:",inline"`
}

Components holds a set of reusable objects for the API specification, as defined in the OpenAPI 3.x specification.

func (*Components) MarshalJSON

func (c *Components) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Components to JSON with support for extensions.

type Config

type Config struct {
	*OpenAPI
	OpenAPIPath                        string
	OpenAPIVersion                     string
	Docs                               DocsConfig
	SchemasPath                        string
	SpecMiddlewares                    Middlewares
	Formats                            map[string]Format
	DefaultFormat                      string
	NoFormatFallback                   bool
	RejectUnknownQueryParameters       bool
	Transformers                       []Transformer
	CreateHooks                        []func(Config) Config
	ErrorHandler                       ErrorHandler
	GenerateOperationID                func(method, path string) string
	GenerateSummary                    func(method, path string) string
	SchemaNamer                        func(t reflect.Type, hint string) string
	InternalSpec                       InternalSpecConfig
	ExcludeHiddenSchemas               bool
	AllowAdditionalPropertiesByDefault bool
	FieldsOptionalByDefault            bool
	ErrorDocs                          map[int]ErrorDoc
}

Config holds the top-level configuration for a neoma API instance, including OpenAPI metadata, content negotiation formats, schema generation options, transformers, middleware, and error handling.

type Contact

type Contact struct {
	Name       string         `yaml:"name,omitempty"`
	URL        string         `yaml:"url,omitempty"`
	Email      string         `yaml:"email,omitempty"`
	Extensions map[string]any `yaml:",inline"`
}

Contact represents the contact information for the exposed API, as defined in the OpenAPI 3.x specification.

func (*Contact) MarshalJSON

func (c *Contact) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Contact to JSON with support for extensions.

type ContentTyper

type ContentTyper interface {
	ContentType(string) string
}

ContentTyper is implemented by response types that need to override the default Content-Type header. The method receives the negotiated content type and returns the actual content type to use.

type Context

type Context interface {
	Operation() *Operation
	Context() context.Context
	TLS() *tls.ConnectionState
	Version() ProtoVersion
	Method() string
	Host() string
	RemoteAddr() string
	URL() url.URL
	Param(name string) string
	Query(name string) string
	Header(name string) string
	EachHeader(cb func(name, value string))
	BodyReader() io.Reader
	GetMultipartForm() (*multipart.Form, error)
	SetReadDeadline(time.Time) error
	SetStatus(code int)
	Status() int
	SetHeader(name, value string)
	AppendHeader(name, value string)

	GetResponseHeader(name string) string
	DeleteResponseHeader(name string)

	BodyWriter() io.Writer

	MatchedPattern() string
}

Context represents the HTTP request and response state for a single API call. It provides read access to the incoming request (method, headers, URL, body) and write access to the outgoing response (status, headers, body). Implementations are supplied by the adapter.

func UnwrapContext

func UnwrapContext(ctx Context) Context

UnwrapContext repeatedly unwraps a wrapped Context until it reaches the innermost adapter-provided Context. This is useful for accessing the original adapter context from middleware that may have wrapped it.

func WithContext

func WithContext(ctx Context, override context.Context) Context

WithContext returns a shallow copy of ctx that uses override as its underlying context.Context. This is useful for attaching deadlines, cancellation signals, or request-scoped values.

func WithValue

func WithValue(ctx Context, key, value any) Context

WithValue returns a shallow copy of ctx with the given key-value pair attached to its underlying context.Context.

type DiscoveredError

type DiscoveredError struct {
	Status int
	Title  string
	Detail string
}

DiscoveredError represents an error response that was automatically discovered during operation registration, such as validation failures or missing required parameters.

type Discriminator

type Discriminator struct {
	PropertyName string            `yaml:"propertyName"`
	Mapping      map[string]string `yaml:"mapping,omitempty"`
}

Discriminator represents an OpenAPI discriminator object, used to aid in serialization, deserialization, and validation of polymorphic schemas (oneOf, anyOf).

func (*Discriminator) MarshalJSON

func (d *Discriminator) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Discriminator to JSON with controlled field ordering and omission behavior.

type DocsConfig

type DocsConfig struct {
	Path        string
	Provider    DocsProvider
	Middlewares Middlewares
	Enabled     bool
}

DocsConfig holds the settings for the API documentation endpoint, including the URL path, the rendering provider, and optional middleware.

type DocsProvider

type DocsProvider interface {
	Render(specURL string, title string) string
}

DocsProvider renders an HTML documentation page for the API. Implementations receive the OpenAPI spec URL and a human-readable title.

type Empty

type Empty struct{}

Empty is used as a response or request body type when no body is expected.

type Encoding

type Encoding struct {
	ContentType   string             `yaml:"contentType,omitempty"`
	Headers       map[string]*Header `yaml:"headers,omitempty"`
	Style         string             `yaml:"style,omitempty"`
	Explode       *bool              `yaml:"explode,omitempty"`
	AllowReserved bool               `yaml:"allowReserved,omitempty"`
	Extensions    map[string]any     `yaml:",inline"`
}

Encoding represents a single encoding definition applied to a single schema property within a media type, as defined in the OpenAPI 3.x specification.

func (*Encoding) MarshalJSON

func (e *Encoding) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Encoding to JSON with support for extensions.

type Error

type Error interface {
	StatusCode() int
	Error() string
}

Error represents an HTTP error response with a status code and message. Implementations typically follow RFC 9457 (Problem Details for HTTP APIs).

type ErrorDetail

type ErrorDetail struct {
	Message  string `json:"message,omitempty" doc:"Error message text"`
	Location string `json:"location,omitempty" doc:"Where the error occurred, e.g. 'body.items[3].tags'"`
	Value    any    `json:"value,omitempty" doc:"The value at the given location"`
}

ErrorDetail represents a single validation or processing error with a human-readable message, the location where the error occurred, and the offending value. It implements both the error and ErrorDetailer interfaces.

func (*ErrorDetail) Error

func (e *ErrorDetail) Error() string

Error returns a human-readable string that includes the message, location, and value when available.

func (*ErrorDetail) ErrorDetail

func (e *ErrorDetail) ErrorDetail() *ErrorDetail

ErrorDetail returns itself, satisfying the ErrorDetailer interface.

type ErrorDetailer

type ErrorDetailer interface {
	ErrorDetail() *ErrorDetail
}

ErrorDetailer is implemented by errors that can provide structured detail information suitable for inclusion in an API error response.

type ErrorDoc

type ErrorDoc struct {
	Title       string
	Description string
	Entries     []ErrorDocEntry
	HTML        string // if set, renders this directly instead of the default template
}

ErrorDoc defines the documentation page for a specific HTTP error status code. When HTML is set, it is rendered directly; otherwise, the default template is used with Title, Description, and Entries.

type ErrorDocEntry

type ErrorDocEntry struct {
	Cause string
	Fix   string
}

ErrorDocEntry describes a single error scenario with its cause and recommended fix, for use in human-readable error documentation pages.

type ErrorHandler

type ErrorHandler interface {
	NewError(status int, msg string, errs ...error) Error
	NewErrorWithContext(ctx Context, status int, msg string, errs ...error) Error
	ErrorSchema(registry Registry) *Schema
	ErrorContentType(ct string) string
}

ErrorHandler defines how the framework creates and serializes error responses. Implementations control the error body schema, content type, and construction logic (e.g., RFC 9457 problem details).

type ErrorResponseConfig

type ErrorResponseConfig struct {
	Description string
	Headers     map[string]*Param
	Schema      *Schema
}

ErrorResponseConfig holds configuration for a specific error response status code, allowing customization of the description, headers, and schema.

type Example

type Example struct {
	Ref           string         `yaml:"$ref,omitempty"`
	Summary       string         `yaml:"summary,omitempty"`
	Description   string         `yaml:"description,omitempty"`
	Value         any            `yaml:"value,omitempty"`
	ExternalValue string         `yaml:"externalValue,omitempty"`
	Extensions    map[string]any `yaml:",inline"`
}

Example represents an example value for a media type, parameter, or schema, as defined in the OpenAPI 3.x specification.

func (*Example) MarshalJSON

func (e *Example) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Example to JSON with support for extensions.

type ExampleProvider

type ExampleProvider interface {
	Example() any
}

ExampleProvider is implemented by types that can return an example value for use in OpenAPI documentation.

type ExternalDocs

type ExternalDocs struct {
	Description string         `yaml:"description,omitempty"`
	URL         string         `yaml:"url"`
	Extensions  map[string]any `yaml:",inline"`
}

ExternalDocs represents a reference to external documentation, as defined in the OpenAPI 3.x specification.

func (*ExternalDocs) MarshalJSON

func (e *ExternalDocs) MarshalJSON() ([]byte, error)

MarshalJSON serializes the ExternalDocs to JSON with support for extensions.

type FormFile

type FormFile struct {
	multipart.File
	*multipart.FileHeader
}

FormFile represents a single file uploaded via a multipart form request.

type Format

type Format struct {
	Marshal   func(writer io.Writer, v any) error
	Unmarshal func(data []byte, v any) error
}

Format defines a content type's marshaling and unmarshaling functions for encoding response bodies and decoding request bodies.

type Header = Param

Header is an alias for Param, representing an HTTP header parameter as defined in the OpenAPI 3.x specification.

type Headerer

type Headerer interface {
	GetHeaders() http.Header
}

Headerer is implemented by error or response types that provide additional HTTP headers to include in the response.

type HiddenOperationsProvider

type HiddenOperationsProvider interface {
	HiddenOperations() []*Operation
	AddHiddenOperation(op *Operation)
}

HiddenOperationsProvider is implemented by adapters that support operations excluded from the public OpenAPI spec but still routable (for example, internal health checks or spec endpoints).

type Info

type Info struct {
	Title          string         `yaml:"title"`
	Description    string         `yaml:"description,omitempty"`
	TermsOfService string         `yaml:"termsOfService,omitempty"`
	Contact        *Contact       `yaml:"contact,omitempty"`
	License        *License       `yaml:"license,omitempty"`
	Version        string         `yaml:"version"`
	Extensions     map[string]any `yaml:",inline"`
}

Info represents the metadata about the API, as defined in the OpenAPI 3.x specification. The Title and Version fields are required.

func (*Info) MarshalJSON

func (i *Info) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Info to JSON with support for extensions.

type InternalSpecConfig

type InternalSpecConfig struct {
	Path        string
	DocsPath    string
	Middlewares Middlewares
	Enabled     bool
}

InternalSpecConfig holds the settings for the internal OpenAPI spec endpoint, which serves the raw specification for internal tooling.

type JSONFieldInfo

type JSONFieldInfo struct {
	Name  string
	Value any
	Omit  OmitType
}

JSONFieldInfo describes a single field for use with MarshalJSON, including its JSON key name, value, and omission strategy.

type License

type License struct {
	Name       string         `yaml:"name"`
	Identifier string         `yaml:"identifier,omitempty"`
	URL        string         `yaml:"url,omitempty"`
	Extensions map[string]any `yaml:",inline"`
}

License represents the license information for the exposed API, as defined in the OpenAPI 3.x specification.

func (*License) MarshalJSON

func (l *License) MarshalJSON() ([]byte, error)

MarshalJSON serializes the License to JSON with support for extensions.

type Link struct {
	Ref          string         `yaml:"$ref,omitempty"`
	OperationRef string         `yaml:"operationRef,omitempty"`
	OperationID  string         `yaml:"operationId,omitempty"`
	Parameters   map[string]any `yaml:"parameters,omitempty"`
	RequestBody  any            `yaml:"requestBody,omitempty"`
	Description  string         `yaml:"description,omitempty"`
	Server       *Server        `yaml:"server,omitempty"`
	Extensions   map[string]any `yaml:",inline"`
}

Link represents a possible design-time link for a response, as defined in the OpenAPI 3.x specification.

func (*Link) MarshalJSON

func (l *Link) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Link to JSON with support for extensions.

type Linker

type Linker interface {
	GetType() string
}

Linker is implemented by response types that provide a link relation type, enabling automatic Link header generation per RFC 8288.

type MediaType

type MediaType struct {
	Schema     *Schema              `yaml:"schema,omitempty"`
	Example    any                  `yaml:"example,omitempty"`
	Examples   map[string]*Example  `yaml:"examples,omitempty"`
	Encoding   map[string]*Encoding `yaml:"encoding,omitempty"`
	Extensions map[string]any       `yaml:",inline"`
}

MediaType represents a media type with a schema and optional examples, as defined in the OpenAPI 3.x specification.

func (*MediaType) MarshalJSON

func (m *MediaType) MarshalJSON() ([]byte, error)

MarshalJSON serializes the MediaType to JSON with support for extensions.

type MiddlewareFunc

type MiddlewareFunc func(ctx Context, next func(Context))

MiddlewareFunc is a function that wraps an operation handler, allowing pre- and post-processing of requests. Call next to continue the chain.

type Middlewares

type Middlewares []MiddlewareFunc

Middlewares is an ordered list of middleware functions.

func (Middlewares) Handler

func (m Middlewares) Handler(endpoint func(Context)) func(Context)

Handler composes the middleware chain around the given endpoint and returns a single handler function that executes them in order.

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `yaml:"authorizationUrl,omitempty"`
	TokenURL         string            `yaml:"tokenUrl"`
	RefreshURL       string            `yaml:"refreshUrl,omitempty"`
	Scopes           map[string]string `yaml:"scopes"`
	Extensions       map[string]any    `yaml:",inline"`
}

OAuthFlow represents the configuration for an OAuth 2.0 flow, as defined in the OpenAPI 3.x specification.

func (*OAuthFlow) MarshalJSON

func (o *OAuthFlow) MarshalJSON() ([]byte, error)

MarshalJSON serializes the OAuthFlow to JSON with support for extensions.

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow     `yaml:"implicit,omitempty"`
	Password          *OAuthFlow     `yaml:"password,omitempty"`
	ClientCredentials *OAuthFlow     `yaml:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow     `yaml:"authorizationCode,omitempty"`
	Extensions        map[string]any `yaml:",inline"`
}

OAuthFlows represents the available OAuth 2.0 flows (implicit, password, client credentials, authorization code), as defined in the OpenAPI 3.x specification.

func (*OAuthFlows) MarshalJSON

func (o *OAuthFlows) MarshalJSON() ([]byte, error)

MarshalJSON serializes the OAuthFlows to JSON with support for extensions.

type OmitType

type OmitType int

OmitType controls the omission behavior of a JSON field during marshaling.

const (
	// OmitNever always includes the field in the JSON output.
	OmitNever OmitType = iota
	// OmitEmpty omits the field when its value is the zero value for its type.
	OmitEmpty
	// OmitNil omits the field when its value is nil.
	OmitNil
)

OmitType values control when a JSON field is omitted from output.

type OpenAPI

type OpenAPI struct {
	OpenAPI string `yaml:"openapi"`

	Info         *Info                 `yaml:"info"`
	Servers      []*Server             `yaml:"servers,omitempty"`
	Paths        map[string]*PathItem  `yaml:"paths,omitempty"`
	Components   *Components           `yaml:"components,omitempty"`
	Security     []map[string][]string `yaml:"security,omitempty"`
	Tags         []*Tag                `yaml:"tags,omitempty"`
	ExternalDocs *ExternalDocs         `yaml:"externalDocs,omitempty"`
	Extensions   map[string]any        `yaml:",inline"`

	// OnAddOperation is called when a new operation is added to the spec.
	// This is useful for transformers that need to modify the spec.
	OnAddOperation []func(oapi *OpenAPI, op *Operation) `yaml:"-"`
}

OpenAPI represents the root document object of an OpenAPI 3.x specification. It contains all API metadata, paths, components, and security definitions.

func (*OpenAPI) AddOperation

func (o *OpenAPI) AddOperation(op *Operation)

AddOperation registers an operation under its path and method in the spec, then invokes any OnAddOperation hooks.

func (*OpenAPI) MarshalJSON

func (o *OpenAPI) MarshalJSON() ([]byte, error)

MarshalJSON serializes the OpenAPI document to JSON with support for extensions.

type Operation

type Operation struct {
	Method                       string                       `yaml:"-"`
	Path                         string                       `yaml:"-"`
	DefaultStatus                int                          `yaml:"-"`
	MaxBodyBytes                 int64                        `yaml:"-"`
	BodyReadTimeout              time.Duration                `yaml:"-"`
	Errors                       []int                        `yaml:"-"`
	ErrorHeaders                 map[string]*Param            `yaml:"-"`
	ErrorResponses               map[int]*ErrorResponseConfig `yaml:"-"`
	SkipValidateParams           bool                         `yaml:"-"`
	SkipValidateBody             bool                         `yaml:"-"`
	SkipDiscoveredErrors         bool                         `yaml:"-"`
	ErrorExamples                map[int]map[string]*Example  `yaml:"-"`
	RejectUnknownQueryParameters bool                         `yaml:"-"`
	Hidden                       bool                         `yaml:"-"`
	HiddenParameters             []*Param                     `yaml:"-"`
	Metadata                     map[string]any               `yaml:"-"`
	Middlewares                  Middlewares                  `yaml:"-"`

	Tags         []string                        `yaml:"tags,omitempty"`
	Summary      string                          `yaml:"summary,omitempty"`
	Description  string                          `yaml:"description,omitempty"`
	ExternalDocs *ExternalDocs                   `yaml:"externalDocs,omitempty"`
	OperationID  string                          `yaml:"operationId,omitempty"`
	Parameters   []*Param                        `yaml:"parameters,omitempty"`
	RequestBody  *RequestBody                    `yaml:"requestBody,omitempty"`
	Responses    map[string]*Response            `yaml:"responses,omitempty"`
	Callbacks    map[string]map[string]*PathItem `yaml:"callbacks,omitempty"`
	Deprecated   bool                            `yaml:"deprecated,omitempty"`
	Security     []map[string][]string           `yaml:"security,omitempty"`
	Servers      []*Server                       `yaml:"servers,omitempty"`
	Extensions   map[string]any                  `yaml:",inline"`
}

Operation represents a single API operation on a path, combining the OpenAPI 3.x operation object fields (tags, summary, parameters, responses, etc.) with framework-specific settings (method, path, body limits, validation flags, middleware).

func (*Operation) MarshalJSON

func (o *Operation) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Operation to JSON, including only the OpenAPI spec fields and any extensions. Framework-specific fields are excluded.

type Param

type Param struct {
	Ref             string              `yaml:"$ref,omitempty"`
	Name            string              `yaml:"name,omitempty"`
	In              string              `yaml:"in,omitempty"`
	Description     string              `yaml:"description,omitempty"`
	Required        bool                `yaml:"required,omitempty"`
	Deprecated      bool                `yaml:"deprecated,omitempty"`
	AllowEmptyValue bool                `yaml:"allowEmptyValue,omitempty"`
	Style           string              `yaml:"style,omitempty"`
	Explode         *bool               `yaml:"explode,omitempty"`
	AllowReserved   bool                `yaml:"allowReserved,omitempty"`
	Schema          *Schema             `yaml:"schema,omitempty"`
	Example         any                 `yaml:"example,omitempty"`
	Examples        map[string]*Example `yaml:"examples,omitempty"`
	Extensions      map[string]any      `yaml:",inline"`
}

Param represents a parameter passed to an operation via path, query, header, or cookie, as defined in the OpenAPI 3.x specification.

func (*Param) MarshalJSON

func (p *Param) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Param to JSON with support for extensions.

type PathBuffer

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

PathBuffer is an efficient builder for dot-separated validation error paths such as "body.items[3].name". It supports push/pop semantics so that path segments can be appended while descending into nested structures and removed when returning.

func NewPathBuffer

func NewPathBuffer(buf []byte, offset int) *PathBuffer

NewPathBuffer returns a PathBuffer initialized with the given backing byte slice and offset.

func (*PathBuffer) Bytes

func (b *PathBuffer) Bytes() []byte

Bytes returns the current path as a byte slice.

func (*PathBuffer) Len

func (b *PathBuffer) Len() int

Len returns the current length of the path in bytes.

func (*PathBuffer) Pop

func (b *PathBuffer) Pop()

Pop removes the last segment (property name or array index) from the path.

func (*PathBuffer) Push

func (b *PathBuffer) Push(s string)

Push appends a dot-separated property name to the path (e.g. "name").

func (*PathBuffer) PushIndex

func (b *PathBuffer) PushIndex(i int)

PushIndex appends a bracketed array index to the path (e.g. "[3]").

func (*PathBuffer) Reset

func (b *PathBuffer) Reset()

Reset clears the path buffer, allowing it to be reused.

func (*PathBuffer) String

func (b *PathBuffer) String() string

String returns the current path as a string.

func (*PathBuffer) With

func (b *PathBuffer) With(s string) string

With temporarily pushes a property name, snapshots the path as a string, then pops it. This is a convenience for one-off path construction.

func (*PathBuffer) WithIndex

func (b *PathBuffer) WithIndex(i int) string

WithIndex temporarily pushes an array index, snapshots the path as a string, then pops it. This is a convenience for one-off path construction.

type PathItem

type PathItem struct {
	Ref         string         `yaml:"$ref,omitempty"`
	Summary     string         `yaml:"summary,omitempty"`
	Description string         `yaml:"description,omitempty"`
	Get         *Operation     `yaml:"get,omitempty"`
	Put         *Operation     `yaml:"put,omitempty"`
	Post        *Operation     `yaml:"post,omitempty"`
	Delete      *Operation     `yaml:"delete,omitempty"`
	Options     *Operation     `yaml:"options,omitempty"`
	Head        *Operation     `yaml:"head,omitempty"`
	Patch       *Operation     `yaml:"patch,omitempty"`
	Trace       *Operation     `yaml:"trace,omitempty"`
	Servers     []*Server      `yaml:"servers,omitempty"`
	Parameters  []*Param       `yaml:"parameters,omitempty"`
	Extensions  map[string]any `yaml:",inline"`
}

PathItem represents the operations available on a single API path, as defined in the OpenAPI 3.x specification.

func (*PathItem) MarshalJSON

func (p *PathItem) MarshalJSON() ([]byte, error)

MarshalJSON serializes the PathItem to JSON with support for extensions.

type ProtoVersion

type ProtoVersion struct {
	Proto      string
	ProtoMajor int
	ProtoMinor int
}

ProtoVersion holds the HTTP protocol version of a request (for example, "HTTP/1.1" or "HTTP/2.0").

type Registry

type Registry interface {
	Schema(t reflect.Type, allowRef bool, hint string) *Schema
	SchemaFromRef(ref string) *Schema
	TypeFromRef(ref string) reflect.Type
	Map() map[string]*Schema
	RegisterTypeAlias(t reflect.Type, alias reflect.Type)
}

Registry manages JSON Schema definitions and provides methods for generating schemas from Go types, resolving $ref references, and registering type aliases.

type RequestBody

type RequestBody struct {
	Ref         string                `yaml:"$ref,omitempty"`
	Description string                `yaml:"description,omitempty"`
	Content     map[string]*MediaType `yaml:"content"`
	Required    bool                  `yaml:"required,omitempty"`
	Extensions  map[string]any        `yaml:",inline"`
}

RequestBody represents the request body for an operation, as defined in the OpenAPI 3.x specification.

func (*RequestBody) MarshalJSON

func (r *RequestBody) MarshalJSON() ([]byte, error)

MarshalJSON serializes the RequestBody to JSON with support for extensions.

type Resolver

type Resolver interface {
	Resolve(ctx Context) []error
}

Resolver is implemented by input types that need custom logic to extract or validate values from the request. Returned errors are added to the validation error response.

type ResolverWithPath

type ResolverWithPath interface {
	Resolve(ctx Context, prefix *PathBuffer) []error
}

ResolverWithPath is like Resolver but receives a PathBuffer so that returned errors can include the field's location path for structured error reporting.

type Response

type Response struct {
	Ref         string                `yaml:"$ref,omitempty"`
	Description string                `yaml:"description,omitempty"`
	Headers     map[string]*Param     `yaml:"headers,omitempty"`
	Content     map[string]*MediaType `yaml:"content,omitempty"`
	Links       map[string]*Link      `yaml:"links,omitempty"`
	Extensions  map[string]any        `yaml:",inline"`
}

Response represents a single response from an API operation, including headers, content, and links, as defined in the OpenAPI 3.x specification.

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Response to JSON with support for extensions.

type Schema

type Schema struct {
	Type                 string              `yaml:"type,omitempty"`
	Nullable             bool                `yaml:"-"`
	Title                string              `yaml:"title,omitempty"`
	Description          string              `yaml:"description,omitempty"`
	Ref                  string              `yaml:"$ref,omitempty"`
	Format               string              `yaml:"format,omitempty"`
	ContentEncoding      string              `yaml:"contentEncoding,omitempty"`
	Default              any                 `yaml:"default,omitempty"`
	Examples             []any               `yaml:"examples,omitempty"`
	Items                *Schema             `yaml:"items,omitempty"`
	AdditionalProperties any                 `yaml:"additionalProperties,omitempty"`
	Properties           map[string]*Schema  `yaml:"properties,omitempty"`
	Enum                 []any               `yaml:"enum,omitempty"`
	Minimum              *float64            `yaml:"minimum,omitempty"`
	ExclusiveMinimum     *float64            `yaml:"exclusiveMinimum,omitempty"`
	Maximum              *float64            `yaml:"maximum,omitempty"`
	ExclusiveMaximum     *float64            `yaml:"exclusiveMaximum,omitempty"`
	MultipleOf           *float64            `yaml:"multipleOf,omitempty"`
	MinLength            *int                `yaml:"minLength,omitempty"`
	MaxLength            *int                `yaml:"maxLength,omitempty"`
	Pattern              string              `yaml:"pattern,omitempty"`
	PatternDescription   string              `yaml:"patternDescription,omitempty"`
	MinItems             *int                `yaml:"minItems,omitempty"`
	MaxItems             *int                `yaml:"maxItems,omitempty"`
	UniqueItems          bool                `yaml:"uniqueItems,omitempty"`
	Required             []string            `yaml:"required,omitempty"`
	MinProperties        *int                `yaml:"minProperties,omitempty"`
	MaxProperties        *int                `yaml:"maxProperties,omitempty"`
	ReadOnly             bool                `yaml:"readOnly,omitempty"`
	WriteOnly            bool                `yaml:"writeOnly,omitempty"`
	Deprecated           bool                `yaml:"deprecated,omitempty"`
	Extensions           map[string]any      `yaml:",inline"`
	DependentRequired    map[string][]string `yaml:"dependentRequired,omitempty"`

	OneOf []*Schema `yaml:"oneOf,omitempty"`
	AnyOf []*Schema `yaml:"anyOf,omitempty"`
	AllOf []*Schema `yaml:"allOf,omitempty"`
	Not   *Schema   `yaml:"not,omitempty"`

	Discriminator *Discriminator `yaml:"discriminator,omitempty"`

	PatternRe     *regexp.Regexp  `yaml:"-"`
	RequiredMap   map[string]bool `yaml:"-"`
	PropertyNames []string        `yaml:"-"`
	Hidden        bool            `yaml:"-"`

	MsgEnum              string                       `yaml:"-"`
	MsgMinimum           string                       `yaml:"-"`
	MsgExclusiveMinimum  string                       `yaml:"-"`
	MsgMaximum           string                       `yaml:"-"`
	MsgExclusiveMaximum  string                       `yaml:"-"`
	MsgMultipleOf        string                       `yaml:"-"`
	MsgMinLength         string                       `yaml:"-"`
	MsgMaxLength         string                       `yaml:"-"`
	MsgPattern           string                       `yaml:"-"`
	MsgMinItems          string                       `yaml:"-"`
	MsgMaxItems          string                       `yaml:"-"`
	MsgMinProperties     string                       `yaml:"-"`
	MsgMaxProperties     string                       `yaml:"-"`
	MsgRequired          map[string]string            `yaml:"-"`
	MsgDependentRequired map[string]map[string]string `yaml:"-"`
}

Schema represents a JSON Schema document as defined by the JSON Schema specification (draft 2020-12). It is used for request/response validation and OpenAPI spec generation. Fields prefixed with Msg are precomputed validation error messages populated by Schema.PrecomputeMessages.

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Schema to JSON, handling nullable types, hidden properties, and extension fields.

func (*Schema) PrecomputeMessages

func (s *Schema) PrecomputeMessages()

PrecomputeMessages populates the Msg fields with formatted validation error messages and builds lookup structures such as RequiredMap and PropertyNames. It recurses into sub-schemas (items, properties, oneOf, anyOf, allOf, not). Call this after constructing or modifying a schema to prepare it for validation.

type SchemaProvider

type SchemaProvider interface {
	Schema(r Registry) *Schema
}

SchemaProvider is implemented by types that provide a custom JSON Schema representation instead of relying on automatic schema generation.

type SchemaTransformer

type SchemaTransformer interface {
	TransformSchema(r Registry, s *Schema) *Schema
}

SchemaTransformer is implemented by types that need to modify their auto-generated JSON Schema after it has been created by the registry.

type SecurityScheme

type SecurityScheme struct {
	Type             string         `yaml:"type"`
	Description      string         `yaml:"description,omitempty"`
	Name             string         `yaml:"name,omitempty"`
	In               string         `yaml:"in,omitempty"`
	Scheme           string         `yaml:"scheme,omitempty"`
	BearerFormat     string         `yaml:"bearerFormat,omitempty"`
	Flows            *OAuthFlows    `yaml:"flows,omitempty"`
	OpenIDConnectURL string         `yaml:"openIdConnectUrl,omitempty"`
	Extensions       map[string]any `yaml:",inline"`
}

SecurityScheme represents a security scheme that can be used by API operations (e.g., HTTP authentication, API key, OAuth 2.0, OpenID Connect), as defined in the OpenAPI 3.x specification.

func (*SecurityScheme) MarshalJSON

func (s *SecurityScheme) MarshalJSON() ([]byte, error)

MarshalJSON serializes the SecurityScheme to JSON with support for extensions.

type Server

type Server struct {
	URL         string                     `yaml:"url"`
	Description string                     `yaml:"description,omitempty"`
	Variables   map[string]*ServerVariable `yaml:"variables,omitempty"`
	Extensions  map[string]any             `yaml:",inline"`
}

Server represents a server that hosts the API, as defined in the OpenAPI 3.x specification. The URL field may contain variable substitutions.

func (*Server) MarshalJSON

func (s *Server) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Server to JSON with support for extensions.

type ServerVariable

type ServerVariable struct {
	Enum        []string       `yaml:"enum,omitempty"`
	Default     string         `yaml:"default"`
	Description string         `yaml:"description,omitempty"`
	Extensions  map[string]any `yaml:",inline"`
}

ServerVariable represents a server variable for server URL template substitution, as defined in the OpenAPI 3.x specification.

func (*ServerVariable) MarshalJSON

func (v *ServerVariable) MarshalJSON() ([]byte, error)

MarshalJSON serializes the ServerVariable to JSON with support for extensions.

type StreamResponse

type StreamResponse struct {
	Body func(ctx Context, api API)
}

StreamResponse allows handlers to write directly to the response body using a streaming callback instead of returning a serializable value.

type Tag

type Tag struct {
	Name         string         `yaml:"name"`
	Description  string         `yaml:"description,omitempty"`
	Tags         []*Tag         `yaml:"tags,omitempty"`
	ExternalDocs *ExternalDocs  `yaml:"externalDocs,omitempty"`
	Extensions   map[string]any `yaml:",inline"`
}

Tag represents a tag for API documentation control, allowing operations to be grouped by resources or other qualifiers, as defined in the OpenAPI 3.x specification.

func (*Tag) MarshalJSON

func (t *Tag) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Tag to JSON with support for extensions.

type Transformer

type Transformer func(ctx Context, status string, v any) (any, error)

Transformer is a function that can modify or replace a response value before it is serialized. The status parameter is the HTTP status code as a string.

type ValidateMode

type ValidateMode int

ValidateMode controls which validation rules apply, distinguishing between data read from the server (responses) and data written to the server (requests).

const (
	// ModeReadFromServer applies validation rules for server responses.
	ModeReadFromServer ValidateMode = iota

	// ModeWriteToServer applies validation rules for client requests.
	ModeWriteToServer
)

type ValidateResult

type ValidateResult struct {
	Errors []error
}

ValidateResult collects validation errors produced during schema validation.

func (*ValidateResult) Add

func (r *ValidateResult) Add(path *PathBuffer, v any, msg string)

Add appends a validation error with the given path, offending value, and message.

func (*ValidateResult) Addf

func (r *ValidateResult) Addf(path *PathBuffer, v any, format string, args ...any)

Addf appends a validation error using a fmt.Sprintf-style format string.

func (*ValidateResult) HasErrors

func (r *ValidateResult) HasErrors() bool

HasErrors reports whether any validation errors have been collected.

func (*ValidateResult) Reset

func (r *ValidateResult) Reset()

Reset clears all collected errors, allowing the result to be reused.

Jump to

Keyboard shortcuts

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