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 ¶
- func NewUIHandler(title, specURL, basePath string, renderer UIRenderer) http.Handler
- type APIKey
- type APIKeyIn
- type Collector
- func (c *Collector) AnnotateOperation(method, pattern string, fn func(oc OperationContext) error)
- func (c *Collector) CollectOperation(method, pattern string, handler http.Handler, ...) error
- func (c *Collector) ServeHTTP(w http.ResponseWriter, _ *http.Request)
- func (c *Collector) SkipPath(path string)
- func (c *Collector) SpecConfig() SpecConfig
- type ErrorBody
- type ExternalDocsInfo
- type HTTPBasic
- type HTTPBearer
- type MutualTLS
- type OAuth2
- type OAuth2AuthorizationCodeFlow
- type OAuth2ClientCredentialsFlow
- type OAuth2ImplicitFlow
- type OAuth2PasswordFlow
- type OIDC
- type OpOpt
- func Deprecated() OpOpt
- func Description(s string) OpOpt
- func Errors(statuses ...int) OpOpt
- func ExternalDocs(url, description string) OpOpt
- func NoSecurity() OpOpt
- func OperationID(id string) OpOpt
- func Raw(fn func(oc OperationContext) error) OpOpt
- func RequestExample(name string, example any) OpOpt
- func Response(status int, body any) OpOpt
- func ResponseExample(status int, name string, example any) OpOpt
- func Security(schemeNames ...string) OpOpt
- func Summary(s string) OpOpt
- func Tags(tags ...string) OpOpt
- type OperationContext
- type Preparer
- type Reflector
- type SecurityScheme
- func APIKeyCookie(cookieName string) SecurityScheme
- func APIKeyHeader(headerName string) SecurityScheme
- func APIKeyQuery(paramName string) SecurityScheme
- func BasicAuth() SecurityScheme
- func BearerJWT() SecurityScheme
- func BearerToken(format string) SecurityScheme
- func MutualTLSScheme() SecurityScheme
- func OAuth2AuthorizationCode(authURL, tokenURL string, scopes map[string]string) SecurityScheme
- func OAuth2ClientCredentials(tokenURL string, scopes map[string]string) SecurityScheme
- func OAuth2Implicit(authURL string, scopes map[string]string) SecurityScheme
- func OAuth2Password(tokenURL string, scopes map[string]string) SecurityScheme
- func OIDCScheme(discoveryURL string) SecurityScheme
- type SpecConfig
- type SpecOpt
- func DefaultSecurity(schemeNames ...string) SpecOpt
- func Server(url, description string) SpecOpt
- func SpecDescription(s string) SpecOpt
- func SpecExternalDocs(url, description string) SpecOpt
- func SpecPath(p string) SpecOpt
- func SpecSecurityScheme(name string, scheme SecurityScheme) SpecOpt
- func SpecTag(name, description string) SpecOpt
- func SpecTitle(s string) SpecOpt
- func SpecVersion(s string) SpecOpt
- func UI(r UIRenderer) SpecOpt
- func UIPath(p string) SpecOpt
- type SpecServer
- type SpecTagInfo
- type UIRenderer
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 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:
- Pre-registered annotations from AnnotateOperation.
- The handler's Preparer (if the http.Handler implements openapi.Preparer).
- 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 ¶
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 ¶
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 ¶
ExternalDocsInfo is the external documentation block attached to the spec root.
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 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 ¶
OAuth2ClientCredentialsFlow describes the client-credentials flow.
type OAuth2ImplicitFlow ¶
OAuth2ImplicitFlow describes the (deprecated) implicit flow.
type OAuth2PasswordFlow ¶
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 Errors ¶
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 ¶
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 ¶
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 ¶
RequestExample attaches a named example to the request body.
func Response ¶
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 ¶
ResponseExample attaches a named example to a specific response status.
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 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 ¶
DefaultSecurity sets the root-level security requirement applied to every operation that doesn't override it via Security(...) or NoSecurity().
func Server ¶
Server appends a base URL to the spec's servers array. Call multiple times to declare multiple environments.
func SpecDescription ¶
SpecDescription sets the spec's info.description.
func SpecExternalDocs ¶
SpecExternalDocs attaches a single external-docs block to the spec root.
func SpecPath ¶
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.
type SpecServer ¶
SpecServer is one entry in the spec's servers array.
type SpecTagInfo ¶
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" )
Source Files
¶
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. |