openapi

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package openapi is forge's owned wrapper around the underlying OpenAPI 3.1 reflection engine.

Callers (the rest transport, the JSON:API helpers, the petstore example, downstream services) reference only the types defined in this package; the swaggest/openapi-go dependency lives behind internal/swaggestimpl. Replacing or vendoring the implementation changes only that internal package.

Two distinct option families:

  • SpecOpt — server/spec-level configuration (title, version, servers, security schemes, default security). Applied via rest.WithOpenAPI(...).

  • OpOpt — per-operation metadata (summary, tags, deprecated, errors, security override). Applied via rest.HandlerWithOpenAPI(...).

The Collector is the orchestrator: it walks every leaf route the kit's Router registers, asks the handler to describe itself via the Preparer interface, applies any operation annotations, and emits the resulting OpenAPI 3.1 spec at the configured route.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewUIHandler

func NewUIHandler(title, specURL, basePath string, renderer UIRenderer) http.Handler

NewUIHandler returns an http.Handler that renders the documentation UI at the given basePath, pointing at the supplied specURL.

All three renderer choices currently route through Swagger UI v5; Redoc and Stoplight are placeholders. The handler degrades to Swagger UI rather than 404 so consumer configuration remains valid.

Types

type APIKey

type APIKey struct {
	Name string
	In   APIKeyIn
}

APIKey is the apiKey scheme.

type APIKeyIn

type APIKeyIn string

APIKeyIn identifies where an API key is presented.

const (
	APIKeyInHeader APIKeyIn = "header"
	APIKeyInQuery  APIKeyIn = "query"
	APIKeyInCookie APIKeyIn = "cookie"
)

type Collector

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

Collector orchestrates OpenAPI spec generation across the kit. It owns a Reflector, holds per-route annotation registrations, and serves the final spec JSON.

Lifetime: one Collector per server. Constructed by rest.WithOpenAPI; fed by router.build as routes are registered; queried by the spec endpoint at request time.

All public methods are safe for concurrent use.

func NewCollector

func NewCollector(ref Reflector, cfg SpecConfig) (*Collector, error)

NewCollector returns a Collector backed by the given Reflector and pre-configured with the spec-level options in cfg. Applies defaults (SpecPath, UIPath, …) before propagating into the spec.

func (*Collector) AnnotateOperation

func (c *Collector) AnnotateOperation(method, pattern string, fn func(oc OperationContext) error)

AnnotateOperation registers a setup function for the (method, pattern) operation. Setup runs during CollectOperation, after the handler's own Preparer setup and before the caller-supplied annotations. Useful for cross-cutting concerns (e.g. applying DefaultSecurity).

func (*Collector) CollectOperation

func (c *Collector) CollectOperation(
	method, pattern string,
	handler http.Handler,
	annotations ...func(oc OperationContext) error,
) error

CollectOperation runs the full setup chain for one operation and registers it on the spec:

  1. Pre-registered annotations from AnnotateOperation.
  2. The handler's Preparer (if the http.Handler implements openapi.Preparer).
  3. The caller-supplied annotations passed in this call.

Step 4 (after all setups) applies DefaultSecurity if the operation hasn't already set its own security.

func (*Collector) ServeHTTP

func (c *Collector) ServeHTTP(w http.ResponseWriter, _ *http.Request)

ServeHTTP serves the assembled spec as application/json.

func (*Collector) SkipPath

func (c *Collector) SkipPath(path string)

SkipPath marks a path that should not be collected into the spec. The kit uses this to hide infrastructure routes (the spec endpoint itself, the UI mount, health probes) — they're not part of the service's API surface.

func (*Collector) SpecConfig

func (c *Collector) SpecConfig() SpecConfig

SpecConfig returns the resolved config, including any defaults filled by ApplyDefaults. Used by rest.WithOpenAPI to know which paths to mount the spec + UI at.

type ErrorBody

type ErrorBody struct {
	Error  string `json:"error"`
	Status int    `json:"status"`
}

ErrorBody is the canonical error response shape emitted by the kit's default plain-JSON error encoder. Op-level Errors() declares responses with this body.

type ExternalDocsInfo

type ExternalDocsInfo struct {
	URL         string
	Description string
}

ExternalDocsInfo is the external documentation block attached to the spec root.

type HTTPBasic

type HTTPBasic struct{}

HTTPBasic represents HTTP basic authentication.

type HTTPBearer

type HTTPBearer struct {
	BearerFormat string
}

HTTPBearer represents an HTTP bearer-token scheme (most common for JWT-based auth). BearerFormat is informational, e.g. "JWT".

type MutualTLS

type MutualTLS struct{}

MutualTLS represents the mutualTLS scheme.

type OAuth2

type OAuth2 struct {
	ClientCredentials *OAuth2ClientCredentialsFlow
	AuthorizationCode *OAuth2AuthorizationCodeFlow
	Implicit          *OAuth2ImplicitFlow
	Password          *OAuth2PasswordFlow
}

OAuth2 represents the oauth2 scheme.

Exactly one of Flow* fields should be populated per scheme. Callers should usually use the OAuth2* builder helpers rather than constructing this struct directly.

type OAuth2AuthorizationCodeFlow

type OAuth2AuthorizationCodeFlow struct {
	AuthorizationURL string
	TokenURL         string
	Scopes           map[string]string
}

OAuth2AuthorizationCodeFlow describes the authorization-code flow.

type OAuth2ClientCredentialsFlow

type OAuth2ClientCredentialsFlow struct {
	TokenURL string
	Scopes   map[string]string
}

OAuth2ClientCredentialsFlow describes the client-credentials flow.

type OAuth2ImplicitFlow

type OAuth2ImplicitFlow struct {
	AuthorizationURL string
	Scopes           map[string]string
}

OAuth2ImplicitFlow describes the (deprecated) implicit flow.

type OAuth2PasswordFlow

type OAuth2PasswordFlow struct {
	TokenURL string
	Scopes   map[string]string
}

OAuth2PasswordFlow describes the (deprecated) password flow.

type OIDC

type OIDC struct {
	DiscoveryURL string
}

OIDC represents the openIdConnect scheme. The discovery URL points at the issuer's well-known configuration endpoint.

type OpOpt

type OpOpt func(OperationContext) error

OpOpt is a per-operation option. The kit composes a slice of these into a single function that runs against the OperationContext during spec collection.

func Deprecated

func Deprecated() OpOpt

Deprecated marks the operation as deprecated.

func Description

func Description(s string) OpOpt

Description sets the operation description.

func Errors

func Errors(statuses ...int) OpOpt

Errors is a shorthand for declaring several error responses using the kit's standard ErrorBody schema. Each status maps to a response with the same body shape.

func ExternalDocs

func ExternalDocs(url, description string) OpOpt

ExternalDocs attaches a single external documentation link.

func NoSecurity

func NoSecurity() OpOpt

NoSecurity explicitly clears any default security on the operation, marking it public. Used to override DefaultSecurity for a single route (e.g. POST /login).

func OperationID

func OperationID(id string) OpOpt

OperationID overrides the auto-derived operation ID.

func Raw

func Raw(fn func(oc OperationContext) error) OpOpt

Raw is an escape hatch for callers that need to manipulate the OperationContext directly. Prefer the typed helpers above.

func RequestExample

func RequestExample(name string, example any) OpOpt

RequestExample attaches a named example to the request body.

func Response

func Response(status int, body any) OpOpt

Response declares an additional response with an arbitrary body. Use when the body for a status code differs from the kit standard ErrorBody.

func ResponseExample

func ResponseExample(status int, name string, example any) OpOpt

ResponseExample attaches a named example to a specific response status.

func Security

func Security(schemeNames ...string) OpOpt

Security requires the operation be authorised by all the named schemes. The schemes must be declared at spec level via SecurityScheme.

func Summary

func Summary(s string) OpOpt

Summary sets the operation summary.

func Tags

func Tags(tags ...string) OpOpt

Tags groups the operation under the given tags.

type OperationContext

type OperationContext interface {
	// AddRequest declares the request body shape. Pass a zero value
	// of the request struct; the underlying reflector walks its
	// json/jsonapi tags to produce the JSON Schema.
	AddRequest(body any)

	// AddResponse declares a response for the given HTTP status.
	// May be called multiple times to declare error responses.
	AddResponse(status int, body any)

	// SetSummary sets the operation's short, single-line summary.
	SetSummary(s string)

	// SetDescription sets the operation's longer prose description.
	SetDescription(s string)

	// SetTags groups the operation under one or more tags. The UI
	// uses these to organise the operation list.
	SetTags(tags ...string)

	// SetOperationID sets a globally-unique operation ID. If unset,
	// the reflector derives one from method+path.
	SetOperationID(id string)

	// SetDeprecated marks the operation as deprecated.
	SetDeprecated(b bool)

	// AddRequestExample attaches a named example to the request body.
	AddRequestExample(name string, example any)

	// AddResponseExample attaches a named example to a specific
	// response status.
	AddResponseExample(status int, name string, example any)

	// SetSecurity requires the operation be authorised by all the
	// named schemes (AND semantics). Schemes must be declared at
	// spec level via SecurityScheme. Pass no arguments to explicitly
	// clear any default security (i.e. mark the operation public).
	SetSecurity(schemes ...string)

	// AddExternalDocs attaches a single external documentation link
	// to the operation.
	AddExternalDocs(url, description string)
}

OperationContext is the surface a handler talks to when describing itself for the OpenAPI spec. The kit's handler factories implement Preparer and call AddRequest / AddResponse / setters on this type during spec collection.

type Preparer

type Preparer interface {
	SetupOperation(oc OperationContext) error
}

Preparer is implemented by HTTP handlers that can describe themselves to the OpenAPI Collector. Every kit handler factory emits a value that satisfies Preparer, so the Collector can walk the registered routes and produce the spec without any annotations in code comments.

type Reflector

type Reflector interface {
	// NewOperationContext returns a fresh context for the operation
	// at (method, pattern). Callers fill it via OperationContext
	// methods then pass it back to AddOperation.
	NewOperationContext(method, pattern string) (OperationContext, error)

	// AddOperation registers a fully-described operation on the spec.
	AddOperation(oc OperationContext) error

	// ApplySpecConfig applies spec-level configuration (info, servers,
	// tags, security schemes, default security, external docs).
	ApplySpecConfig(cfg SpecConfig) error

	// SpecJSON returns the assembled spec as JSON bytes.
	SpecJSON() ([]byte, error)
}

Reflector is the engine that builds an OpenAPI 3.1 spec by reflecting Go types provided through OperationContext. Forge owns this interface; the default implementation lives behind internal/swaggestimpl.

func NewReflector

func NewReflector() Reflector

NewReflector returns the default OpenAPI 3.1 reflector — the swaggest-backed implementation.

type SecurityScheme

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

SecurityScheme is the forge representation of an OpenAPI 3.1 security scheme. Each implementation describes one of the schemes the spec supports (http+bearer, apiKey, oauth2, openIdConnect, mutualTLS).

The sealed marker method keeps consumers from defining their own — the bridge in internal/swaggestimpl needs to know every concrete type to translate it into the underlying spec.

func APIKeyCookie

func APIKeyCookie(cookieName string) SecurityScheme

APIKeyCookie is shorthand for an apiKey scheme presented in the named cookie.

func APIKeyHeader

func APIKeyHeader(headerName string) SecurityScheme

APIKeyHeader is shorthand for an apiKey scheme presented in the named HTTP header.

func APIKeyQuery

func APIKeyQuery(paramName string) SecurityScheme

APIKeyQuery is shorthand for an apiKey scheme presented in the named query parameter.

func BasicAuth

func BasicAuth() SecurityScheme

BasicAuth returns a Basic HTTP scheme.

func BearerJWT

func BearerJWT() SecurityScheme

BearerJWT is shorthand for HTTPBearer{BearerFormat: "JWT"}.

func BearerToken

func BearerToken(format string) SecurityScheme

BearerToken returns an HTTP bearer scheme with the given format.

func MutualTLSScheme

func MutualTLSScheme() SecurityScheme

MutualTLSScheme returns a mutualTLS scheme.

func OAuth2AuthorizationCode

func OAuth2AuthorizationCode(authURL, tokenURL string, scopes map[string]string) SecurityScheme

OAuth2AuthorizationCode is shorthand for the authorization-code flow.

func OAuth2ClientCredentials

func OAuth2ClientCredentials(tokenURL string, scopes map[string]string) SecurityScheme

OAuth2ClientCredentials is shorthand for the client-credentials flow.

func OAuth2Implicit

func OAuth2Implicit(authURL string, scopes map[string]string) SecurityScheme

OAuth2Implicit is shorthand for the implicit flow (deprecated by the OAuth 2.0 BCP but still occasionally encountered).

func OAuth2Password

func OAuth2Password(tokenURL string, scopes map[string]string) SecurityScheme

OAuth2Password is shorthand for the resource-owner-password flow (deprecated by the OAuth 2.0 BCP).

func OIDCScheme

func OIDCScheme(discoveryURL string) SecurityScheme

OIDCScheme returns an openIdConnect scheme. (Named OIDCScheme rather than OIDC to avoid colliding with the OIDC struct type.)

type SpecConfig

type SpecConfig struct {
	Title        string
	Version      string
	Description  string
	SpecPath     string
	UIPath       string
	UIRenderer   UIRenderer
	Servers      []SpecServer
	Tags         []SpecTagInfo
	ExternalDocs *ExternalDocsInfo

	SecuritySchemes map[string]SecurityScheme
	DefaultSecurity []string
}

SpecConfig captures spec-level configuration assembled by SpecOpts. Consumed by rest.WithOpenAPI to wire the Collector and the spec/UI routes on the server.

func (*SpecConfig) ApplyDefaults

func (c *SpecConfig) ApplyDefaults()

ApplyDefaults fills empty fields with sensible defaults. Called by the rest package before constructing the Collector.

type SpecOpt

type SpecOpt func(*SpecConfig)

SpecOpt mutates a SpecConfig as it's assembled. rest.WithOpenAPI composes a slice of these into the final config.

func DefaultSecurity

func DefaultSecurity(schemeNames ...string) SpecOpt

DefaultSecurity sets the root-level security requirement applied to every operation that doesn't override it via Security(...) or NoSecurity().

func Server

func Server(url, description string) SpecOpt

Server appends a base URL to the spec's servers array. Call multiple times to declare multiple environments.

func SpecDescription

func SpecDescription(s string) SpecOpt

SpecDescription sets the spec's info.description.

func SpecExternalDocs

func SpecExternalDocs(url, description string) SpecOpt

SpecExternalDocs attaches a single external-docs block to the spec root.

func SpecPath

func SpecPath(p string) SpecOpt

SpecPath overrides the default URL the OpenAPI JSON is served at (default "/openapi.json").

func SpecSecurityScheme

func SpecSecurityScheme(name string, scheme SecurityScheme) SpecOpt

SpecSecurityScheme registers a named security scheme under components.securitySchemes. Reference the same name from operation Security(...) opts or from DefaultSecurity.

func SpecTag

func SpecTag(name, description string) SpecOpt

SpecTag declares a top-level tag with a description, used by UIs to group and describe sets of operations.

func SpecTitle

func SpecTitle(s string) SpecOpt

SpecTitle sets the spec's info.title.

func SpecVersion

func SpecVersion(s string) SpecOpt

SpecVersion sets the spec's info.version.

func UI

func UI(r UIRenderer) SpecOpt

UI selects which UI renderer to use (default SwaggerUI).

func UIPath

func UIPath(p string) SpecOpt

UIPath overrides the default URL the UI is served at (default "/docs").

type SpecServer

type SpecServer struct {
	URL         string
	Description string
}

SpecServer is one entry in the spec's servers array.

type SpecTagInfo

type SpecTagInfo struct {
	Name        string
	Description string
}

SpecTagInfo is one entry in the spec's tags array.

type UIRenderer

type UIRenderer string

UIRenderer identifies which interactive documentation UI to serve. Default is SwaggerUI; alternatives are Redoc and StoplightElements (currently both fall back to Swagger UI; static assets for the alternative renderers can be plugged in later without changing the public API).

const (
	// SwaggerUI renders Swagger UI v5 with Authorize button,
	// "Try it out", and the server dropdown.
	SwaggerUI UIRenderer = "swagger-ui"

	// Redoc renders Redoc's three-pane reference layout. Read-only.
	Redoc UIRenderer = "redoc"

	// StoplightElements renders Stoplight Elements (a Redoc-style
	// reference with optional try-it-out).
	StoplightElements UIRenderer = "stoplight"
)

Directories

Path Synopsis
internal
swaggestimpl
Package swaggestimpl is the sole importer of github.com/swaggest/openapi-go in the forge repo.
Package swaggestimpl is the sole importer of github.com/swaggest/openapi-go in the forge repo.

Jump to

Keyboard shortcuts

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