openapi

package
v1.36.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handler

func Handler(provider DocumentProvider) http.Handler

Handler builds an http.Handler that serves the document as JSON.

func HandlerFunc

func HandlerFunc(provider DocumentProvider) http.HandlerFunc

HandlerFunc adapts a provider into a GET-friendly handler func.

func JSONContent

func JSONContent(schema Schema) map[string]MediaType

func Marshal

func Marshal(doc *Document) ([]byte, error)

func PublicSecurity

func PublicSecurity() *[]SecurityRequirement

PublicSecurity returns an explicit empty security override marking an operation as requiring NO authentication, even when the document declares a global security requirement. (A nil Operation.Security inherits the global.) This is a contract DECLARATION only — runtime auth enforcement is the app middleware's responsibility, never the document's.

func RequireSecurity

func RequireSecurity(reqs ...SecurityRequirement) *[]SecurityRequirement

RequireSecurity wraps requirements into the pointer form an Operation's Security field takes; a non-nil value overrides the document's global security for that operation.

func WriteJSON

func WriteJSON(w io.Writer, doc *Document) error

Types

type Change added in v1.31.0

type Change struct {
	// Operation is "METHOD /path", or "" for a document-wide change.
	Operation string `json:"operation,omitempty"`
	// Where names the part of the operation: "request body /title",
	// "parameter query.page", "response 200 /author", "security".
	Where   string `json:"where,omitempty"`
	Message string `json:"message"`
}

Change is one difference between two versions of a document that a client written against the old one would notice.

func BreakingChanges added in v1.31.0

func BreakingChanges(prev, next *Document) []Change

BreakingChanges lists what in next breaks a client written against prev. The rules are the ones a generated client actually trips on, read from the side of whoever sends the request and reads the response:

  • an operation that disappears;
  • a request that must say more: a new required parameter or body field, a parameter or body that becomes required, a narrower type, a tighter bound, an enum value removed;
  • a response that says less: a field removed or no longer required, a changed type, a success status removed, an enum value added (a client switching on it meets a case it does not know);
  • an operation that was public and now asks for credentials.

Additions a client can ignore — a new operation, an optional parameter, a new response field, a wider request bound — are not reported.

func (Change) String added in v1.31.0

func (c Change) String() string

type Components

type Components struct {
	Schemas         map[string]Schema         `json:"schemas,omitempty"`
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
}

type Document

type Document struct {
	OpenAPI    string                `json:"openapi"`
	Info       Info                  `json:"info"`
	Servers    []Server              `json:"servers,omitempty"`
	Security   []SecurityRequirement `json:"security,omitempty"`
	Paths      map[string]PathItem   `json:"paths,omitempty"`
	Components Components            `json:"components,omitempty"`
	// contains filtered or unexported fields
}

Document is a small OpenAPI 3.1 document model used by generated contracts. It intentionally covers the subset Nucleus scaffolds need today.

func NewDocument

func NewDocument(title, version string) *Document

func (*Document) AddSchema

func (d *Document) AddSchema(name string, schema Schema)

func (*Document) AddSecurityScheme

func (d *Document) AddSecurityScheme(name string, scheme SecurityScheme)

AddSecurityScheme registers a named scheme under components.securitySchemes (lazily creating the map). Reference it by the same name from a SecurityRequirement.

func (*Document) EnsureComponents

func (d *Document) EnsureComponents()

func (*Document) EnsurePaths

func (d *Document) EnsurePaths()

func (*Document) FieldSchema added in v1.31.0

func (d *Document) FieldSchema(f reflect.StructField) (Schema, bool)

FieldSchema returns the schema of one struct field as SchemaFor writes it inside its struct, and whether the field is required there. It is for fields that are not part of a JSON body — a query parameter, a header — whose schema and constraints come from the same Go type and tags.

func (*Document) FindOperation added in v1.31.0

func (d *Document) FindOperation(method, path string) (Route, bool)

FindOperation matches a method and a concrete path ("/articles/42") against the document's paths. A path with fewer parameters wins over one with more, so /articles/new is found before /articles/{id}.

func (*Document) MarshalJSON added in v1.31.0

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

MarshalJSON makes a *Document a json.Marshaler, which is how a stable surface that cannot name this experimental package takes one: the framework's WithOpenAPIDocument accepts base documents as json.Marshaler. The bytes are what Marshal writes, without the indent.

func (*Document) SchemaFor added in v1.31.0

func (d *Document) SchemaFor(t reflect.Type) Schema

SchemaFor is SchemaOf for a reflect.Type, for callers that hold a type rather than a type parameter (a framework that recorded a handler's input type at registration, for instance). A nil document still returns the schema; named structs are then inlined instead of referenced.

func (*Document) Validate added in v1.31.0

func (d *Document) Validate(schema Schema, value any) ValidationErrors

Validate checks a decoded JSON value (what encoding/json produces into an any, numbers preferably as json.Number) against schema, resolving $ref in d's components. It returns every departure, not just the first.

func (*Document) ValidateJSON added in v1.31.0

func (d *Document) ValidateJSON(schema Schema, raw []byte) ValidationErrors

ValidateJSON decodes raw and validates it. A body that is not JSON is one error at "body".

func (*Document) ValidateRequest added in v1.31.0

func (d *Document) ValidateRequest(r *http.Request, route Route) ValidationErrors

ValidateRequest checks a request against the operation route describes: its path, query and header parameters (converted from text to the parameter's type first) and its JSON body. The body is read and put back, so the handler still reads it whole.

func (*Document) ValidateResponse added in v1.31.0

func (d *Document) ValidateResponse(route Route, status int, header http.Header, body []byte) ValidationErrors

ValidateResponse checks a response the operation produced: that its status is declared (exactly, as a range such as 2XX, or by default), that its content type is one the response declares, and that its JSON body conforms to the schema.

type DocumentProvider

type DocumentProvider func() *Document

DocumentProvider returns the current OpenAPI document to serve.

type Info

type Info struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

type MediaType

type MediaType struct {
	Schema Schema `json:"schema"`
}

type Operation

type Operation struct {
	OperationID string   `json:"operationId,omitempty"`
	Summary     string   `json:"summary,omitempty"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	// Security overrides the document's global security for this operation. A
	// nil value inherits the global default; a non-nil value (including an empty
	// slice — see PublicSecurity) replaces it. Pointer so an explicit empty
	// override survives JSON marshalling (a plain slice would be omitted).
	Security    *[]SecurityRequirement `json:"security,omitempty"`
	Parameters  []Parameter            `json:"parameters,omitempty"`
	RequestBody *RequestBody           `json:"requestBody,omitempty"`
	Responses   map[string]Response    `json:"responses"`
}

type Parameter

type Parameter struct {
	Name        string `json:"name"`
	In          string `json:"in"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
	Schema      Schema `json:"schema"`
}

func PathParameter

func PathParameter(name string, schema Schema, description string) Parameter

func QueryParameter

func QueryParameter(name string, schema Schema, description string, required bool) Parameter

func SearchQueryParameter

func SearchQueryParameter(description string) Parameter

type PathItem

type PathItem struct {
	Get    *Operation `json:"get,omitempty"`
	Post   *Operation `json:"post,omitempty"`
	Put    *Operation `json:"put,omitempty"`
	Patch  *Operation `json:"patch,omitempty"`
	Delete *Operation `json:"delete,omitempty"`
}

func (PathItem) Operation added in v1.31.0

func (p PathItem) Operation(method string) *Operation

Operation returns the operation the item declares for an HTTP method (case-insensitive), or nil.

func (*PathItem) SetOperation added in v1.31.0

func (p *PathItem) SetOperation(method string, op *Operation) bool

SetOperation sets the operation for an HTTP method and reports whether the item has a slot for it (GET, POST, PUT, PATCH, DELETE).

type RequestBody

type RequestBody struct {
	Required bool                 `json:"required,omitempty"`
	Content  map[string]MediaType `json:"content"`
}

func JSONRequestBody

func JSONRequestBody(schema Schema, required bool) *RequestBody

type Response

type Response struct {
	Description string               `json:"description"`
	Content     map[string]MediaType `json:"content,omitempty"`
}

func EmptyResponse

func EmptyResponse(description string) Response

func ErrorResponse

func ErrorResponse(description string) Response

func ErrorResponses added in v1.31.0

func ErrorResponses(description string, problem bool) Response

ErrorResponses is the error response of an operation in both shapes the framework answers: application/problem+json for a client that prefers it, and application/json carrying the envelope — or problem details too when the application answers every error that way (problem true).

func JSONResponse

func JSONResponse(description string, schema Schema) Response

type Route added in v1.31.0

type Route struct {
	// Template is the document's path ("/articles/{id}").
	Template  string
	Operation *Operation
	// Params holds the values the template's {name} segments captured.
	Params map[string]string
}

Route is one operation of the document matched against a concrete request path.

type Schema

type Schema struct {
	Ref                  string            `json:"$ref,omitempty"`
	Type                 string            `json:"type,omitempty"`
	Format               string            `json:"format,omitempty"`
	Description          string            `json:"description,omitempty"`
	Properties           map[string]Schema `json:"properties,omitempty"`
	Items                *Schema           `json:"items,omitempty"`
	Required             []string          `json:"required,omitempty"`
	AdditionalProperties *Schema           `json:"additionalProperties,omitempty"`

	// Nullable admits JSON null besides Type. OpenAPI 3.1 has no nullable
	// keyword: it is written as a type list, ["string", "null"], and read
	// back from one.
	Nullable bool `json:"-"`

	Enum             []any    `json:"enum,omitempty"`
	Minimum          *float64 `json:"minimum,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
	MinLength        *int     `json:"minLength,omitempty"`
	MaxLength        *int     `json:"maxLength,omitempty"`
	Pattern          string   `json:"pattern,omitempty"`
	MinItems         *int     `json:"minItems,omitempty"`
	MaxItems         *int     `json:"maxItems,omitempty"`
}

func ArraySchema

func ArraySchema(items Schema) Schema

func CollectionEnvelopeSchema

func CollectionEnvelopeSchema(item Schema) Schema

func DataEnvelopeSchema

func DataEnvelopeSchema(data Schema) Schema

func ErrorSchema

func ErrorSchema() Schema

func IDSchema

func IDSchema() Schema

func ObjectSchema

func ObjectSchema(properties map[string]Schema, required ...string) Schema

func ProblemSchema added in v1.31.0

func ProblemSchema() Schema

ProblemSchema is RFC 9457 problem details as the framework writes them: type, title and status always, detail and instance when known, and the framework's code and details as extension members.

func RefSchema

func RefSchema(name string) Schema

func SchemaOf added in v1.31.0

func SchemaOf[T any](doc *Document) Schema

SchemaOf returns the schema of T as encoding/json writes it, registering every named struct type it reaches under the document's components.schemas and answering a $ref to it. It is how a handler's request and response types become the contract without writing them a second time as hand-built schemas:

type Article struct {
    ID    int64  `json:"id"`
    Title string `json:"title" validate:"required,max=200"`
    Body  string `json:"body,omitempty"`
}
ref := openapi.SchemaOf[Article](doc) // {"$ref": "#/components/schemas/Article"}

The rules follow encoding/json, so the schema describes the bytes the handler actually sends:

  • The property name is the json tag's name, or the Go field name when there is no tag; `json:"-"` and unexported fields are left out, and embedded structs are flattened the way encoding/json flattens them.
  • A field is required unless its json tag says omitempty (or omitzero), it is a pointer, or its validate tag says omitempty; `validate:"required"` makes it required regardless. A slice or map without omitempty is required and nullable — encoding/json writes null for a nil one.
  • A pointer is nullable. time.Time is a date-time string, []byte a base64 string, a type that implements encoding.TextMarshaler a string (uuid.UUID carries format uuid), a map an object with additionalProperties, an interface the empty schema.
  • validate tags become constraints: min/max/len (length for strings, items for slices, bounds for numbers), gt/gte/lt/lte, oneof (enum), email, url/uri, uuid, ipv4/ipv6, hostname; after `dive` they apply to the elements. A `doc:"…"` tag becomes the description.

A type that implements json.Marshaler writes what it decides, which no reflection can know: it gets the empty schema and a description saying so, rather than a guess.

func (Schema) MarshalJSON added in v1.31.0

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

MarshalJSON writes Type as a list with "null" when the schema is Nullable — the OpenAPI 3.1 spelling of a nullable type.

func (*Schema) UnmarshalJSON added in v1.31.0

func (s *Schema) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads Type both as a string and as a 3.1 type list; a list that carries "null" sets Nullable.

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement is an OpenAPI Security Requirement Object (§4.8.30): a map of security-scheme name to the scope names it requires. HTTP and apiKey schemes take no scopes, so their requirement value is an empty slice.

func Require

func Require(scheme string, scopes ...string) SecurityRequirement

Require builds a Security Requirement naming one registered scheme, with optional OAuth-style scopes (empty for http/apiKey schemes). A nil scope slice — including a spread nil — is normalised to an empty list, the correct serialisation for a scheme that takes no scopes.

type SecurityScheme

type SecurityScheme struct {
	Type         string `json:"type"` // "http" | "apiKey"
	Description  string `json:"description,omitempty"`
	Scheme       string `json:"scheme,omitempty"`       // type=http: "bearer" | "basic"
	BearerFormat string `json:"bearerFormat,omitempty"` // scheme=bearer: token-shape hint, e.g. "JWT"
	Name         string `json:"name,omitempty"`         // type=apiKey: request element name
	In           string `json:"in,omitempty"`           // type=apiKey: "header" | "query" | "cookie"
}

SecurityScheme is an OpenAPI 3.1 Security Scheme Object (§4.8.27). Nucleus models the two schemes a generated contract realistically needs — HTTP authentication (`type: http`, e.g. `bearer` or `basic`) and API keys (`type: apiKey`). oauth2 / openIdConnect flows are out of scope for the scaffold subset.

func APIKeyScheme

func APIKeyScheme(name, in string) SecurityScheme

APIKeyScheme returns an apiKey Security Scheme carried in the named request element. in is one of "header", "query" or "cookie".

func BearerAuthScheme

func BearerAuthScheme(bearerFormat string) SecurityScheme

BearerAuthScheme returns an HTTP bearer Security Scheme. bearerFormat is an optional hint for the token shape (e.g. "JWT") and may be empty.

type Server

type Server struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

type ValidationError added in v1.31.0

type ValidationError struct {
	// Field is the JSON pointer of the offending value inside the body
	// (/author/name, /tags/2), or "query.page", "path.id", "header.X-Tenant"
	// for a parameter, or "body" for the body as a whole.
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError is one way a value departs from the document: where (a JSON pointer into the value, or the parameter's location and name) and what.

func (ValidationError) String added in v1.31.0

func (e ValidationError) String() string

type ValidationErrors added in v1.31.0

type ValidationErrors []ValidationError

ValidationErrors is a list of departures; its Error joins them.

func (ValidationErrors) Error added in v1.31.0

func (es ValidationErrors) Error() string

Jump to

Keyboard shortcuts

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