spec

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package spec builds OpenAPI 3.0, 3.1, and 3.2 documents from internal *spec.SpecInput values. The three emitters (BuildRoot30, BuildRoot31, and BuildRoot32) share a single emitter struct that handles info, servers, tags, paths, components, security, and webhooks; only the schema builder, the version string, and a few version-gated fields ($self, additionalOperations, webhooks) differ between versions.

The input types (Operation, PathItem, Param, RequestBody, Response, Info, etc.) are version-agnostic. The package also re-exports the security-related types so callers can build a complete spec from a single import.

Index

Constants

View Source
const (
	// SecurityHTTP is an HTTP authentication scheme (bearer, basic, etc.).
	// Set the scheme name (lowercase) via Scheme in SecurityScheme.
	SecurityHTTP SecuritySchemeType = "http"
	// SecurityAPIKey is an API key passed via header, query, or cookie.
	// Set the location via In and the name via Name.
	SecurityAPIKey SecuritySchemeType = "apiKey"
	// SecurityOAuth2 is OAuth 2.0 with one or more flows.
	// Set Flows.
	SecurityOAuth2 SecuritySchemeType = "oauth2"
	// SecurityOpenIDConnect is OpenID Connect discovery.
	// Set OpenIDConnectURL.
	SecurityOpenIDConnect SecuritySchemeType = "openIdConnect"
	// SecurityAPIKeyInHeader means the API key is passed in a header.
	SecurityAPIKeyInHeader = "header"
	// SecurityAPIKeyInQuery means the API key is passed in a query parameter.
	SecurityAPIKeyInQuery = "query"
	// SecurityAPIKeyInCookie means the API key is passed in a cookie.
	SecurityAPIKeyInCookie = "cookie"
)

Variables

This section is empty.

Functions

func BuildRoot30

func BuildRoot30(in SpecInput) map[string]any

BuildRoot30 builds the top-level OpenAPI 3.0 (3.0.4) object.

func BuildRoot31

func BuildRoot31(in SpecInput) map[string]any

BuildRoot31 builds the top-level OpenAPI 3.1 (3.1.2) object.

func BuildRoot32

func BuildRoot32(in SpecInput, selfURL string) map[string]any

BuildRoot32 builds the top-level OpenAPI 3.2.0 object.

func EmitOpenAPI30

func EmitOpenAPI30(in SpecInput) ([]byte, error)

EmitOpenAPI30 produces the OpenAPI 3.0 (3.0.4) JSON bytes for the given input. The result is deterministic across runs: every nested object is emitted from sorted keys (useful for tests and golden files).

func EmitOpenAPI31

func EmitOpenAPI31(in SpecInput) ([]byte, error)

EmitOpenAPI31 produces the OpenAPI 3.1 (3.1.2) JSON bytes for the given input. The output is the 3.0 emitter with two adjustments:

  • Nullable is rendered as a type array ("type": ["T", "null"]) instead of a "nullable": true sibling.
  • The top-level "openapi" field is "3.1.2" and webhooks are emitted.

All other structure is identical to 3.0.

func EmitOpenAPI32

func EmitOpenAPI32(in SpecInput, selfURL string) ([]byte, error)

EmitOpenAPI32 produces the OpenAPI 3.2.0 JSON bytes for the given input.

OpenAPI 3.2 (released 2025-09-19) is a minor version on top of 3.1. The schema body and the per-object structure are the same as 3.1 for the fields stdocs emits. The differences that matter for us are:

  • The "openapi" field is "3.2.0".
  • A "$self" field MAY be set to the canonical URI of the document (passed via the selfURL argument, set with WithSelfURL on the mux). When non-empty, it is emitted at the root of the spec.
  • OAuth flows: 3.2 keeps the four 3.0/3.1 flow types (the "implicit" flow is discouraged by current OAuth guidance but was NOT removed from the spec) and adds a new "deviceAuthorization" flow, which OAuthFlows supports via the DeviceAuthorization field. User flows are forwarded as-is.
  • Streaming media type flags, $dynamicRef, multi-content arrays are 3.2 features we do not yet emit. They are additive and can land in a follow-up without breaking 3.1 or 3.0.

For the parts of the spec that stdocs emits today, a 3.2 document is wire-compatible with 3.1 plus the optional "$self" field. The user-visible constant is OpenAPI32; the body shape is the same as 3.1.

func MarshalJSON

func MarshalJSON(v any) ([]byte, error)

MarshalJSON serializes v to JSON bytes.

func UnmarshalJSON

func UnmarshalJSON(data []byte, v any) error

UnmarshalJSON parses JSON bytes into v.

Types

type Contact

type Contact struct {
	Name  string
	URL   string
	Email string
}

Contact is the OpenAPI "contact" object.

type Info

type Info struct {
	Title          string
	Version        string
	Description    string
	TermsOfService string
	Contact        *Contact
	License        *License
}

Info holds the values for the OpenAPI top-level "info" object.

type License

type License struct {
	Name string
	URL  string
}

License is the OpenAPI "license" object.

type NamedSecurityScheme

type NamedSecurityScheme struct {
	Name   string
	Scheme SecurityScheme
}

NamedSecurityScheme is an internal pair (name, scheme) used when constructing the spec from the registry.

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	// DeviceAuthorizationURL is required for (and only meaningful
	// on) the OpenAPI 3.2 deviceAuthorization flow.
	DeviceAuthorizationURL string
	Scopes                 map[string]string
}

OAuthFlow describes one OAuth flow.

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
	// DeviceAuthorization is the RFC 8628 device flow added in
	// OpenAPI 3.2. It is emitted for every version (3.0/3.1
	// validators will flag it), so only set it on a 3.2 mux. Its
	// flow object requires DeviceAuthorizationURL and TokenURL.
	DeviceAuthorization *OAuthFlow
}

OAuthFlows describes the supported OAuth 2.0 flows.

type Operation

type Operation struct {
	Method      string
	Summary     string
	Description string
	Tags        []string
	OperationID string
	Deprecated  bool
	Parameters  []Param
	RequestBody *RequestBody
	Responses   map[string]*Response // status -> response
	// Security is the list of security requirements for this
	// operation. Each requirement is a map of scheme name to scopes.
	// An empty Security slice means "use the global security"; to
	// opt out of auth on a specific route, set NoSecurity to true
	// (which emits an empty `security: []` array — required by the
	// OpenAPI spec to override a globally-applied scheme).
	Security []SecurityRequirement
	// NoSecurity, when true, emits an empty `security` array on
	// this operation, overriding any global security requirement.
	// See WithNoSecurity in the root package.
	NoSecurity bool
	// ResponseOrder tracks the order in which responses were added
	// to the Responses map. Used by WithExample to pick the
	// "most recent" response when no explicit status is given.
	ResponseOrder []string
	// Extensions is a map of x-* extension fields. These are
	// emitted directly onto the operation object. The reflector
	// uses this to surface warnings about non-standard method
	// names, custom status codes, etc. The map is never modified
	// by the emitter.
	Extensions map[string]any
}

Operation is a single method's worth of metadata for a route.

type Param

type Param struct {
	Name        string
	In          string // "path", "query", "header", "cookie"
	Required    bool
	Description string
	Schema      *schema.Schema
}

Param describes a single OpenAPI parameter (path, query, header, or cookie).

type PathItem

type PathItem struct {
	Path       string
	Operations map[string]*Operation // method -> operation
	Parameters []Param               // path-level, shared across methods
}

PathItem groups operations for a single path across HTTP methods. It also captures path-level parameters (e.g. shared path params).

type RequestBody

type RequestBody struct {
	Description string
	Required    bool
	Schema      *schema.Schema
	ContentType string // defaults to "application/json"
	// Example is the JSON-serialised example value (set via
	// WithExample). nil means no example is set.
	Example any
	// BodyValue is the original Go value passed to WithBody. Used
	// internally to re-derive component schemas at spec-build time.
	BodyValue any
}

RequestBody describes the request body of an operation.

type Response

type Response struct {
	Status      string // e.g. "200", "404", "default"
	Description string
	Schema      *schema.Schema // optional body schema
	Headers     map[string]*schema.Schema
	// Example is the JSON-serialised example value for this response
	// (set via WithExample or WithResponseExample). nil means no
	// example is set. It is not serialized into the spec; the
	// emitter reads it from a parallel field.
	Example any
	// BodyValue is the original Go value passed to WithResponse. It is
	// used internally to re-derive component schemas at spec-build
	// time. It is not serialized into the spec.
	BodyValue any
}

Response describes one response in the OpenAPI "responses" map.

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement is a single entry in the operation's "security" array: a set of scheme names mapped to the scopes required (empty for non-OAuth schemes).

type SecurityScheme

type SecurityScheme struct {
	Type             SecuritySchemeType
	Description      string
	Name             string // for apiKey: the parameter name
	In               string // for apiKey: "header" | "query" | "cookie"
	Scheme           string // for http: "bearer" | "basic" | ...
	BearerFormat     string // for http bearer: e.g. "JWT"
	Flows            *OAuthFlows
	OpenIDConnectURL string
}

SecurityScheme describes one scheme in components.securitySchemes.

type SecuritySchemeType

type SecuritySchemeType string

SecuritySchemeType identifies the kind of security scheme.

type Server

type Server struct {
	URL         string
	Description string
}

Server is the OpenAPI "server" object.

type SpecInput

type SpecInput struct {
	Info            Info
	Servers         []Server
	Tags            []TagDecl
	Paths           []PathItem
	Components      map[string]*schema.Schema
	Version         version.SpecVersion
	SecuritySchemes []NamedSecurityScheme
	GlobalSecurity  []SecurityRequirement
	Webhooks        map[string]Webhook
}

SpecInput is the input to an emitter. It is produced by the registry in spec.go; emitters below consume it and produce the OpenAPI JSON bytes.

type TagDecl

type TagDecl struct {
	Name        string
	Description string
}

TagDecl declares a top-level tag and its description. Tags attached to operations (via stdocs.Tags) are auto-collected; this type is for the optional extended description.

type Webhook

type Webhook struct {
	// Method is the HTTP method (POST, GET, etc.) used to deliver
	// the webhook payload. Required.
	Method string
	// Summary is a short description.
	Summary string
	// Description is a long description (Markdown).
	Description string
	// OperationID identifies the webhook uniquely within the API.
	OperationID string
	// RequestBody is the payload structure (optional).
	RequestBody *RequestBody
	// Responses lists expected responses (e.g. 200, 202).
	Responses map[string]*Response
}

Webhook describes an OpenAPI 3.1 webhook. A webhook is a path-and- method pair (like a regular operation) but is documented under "webhooks" rather than "paths". Webhooks are emitted for 3.1 and 3.2, and ignored when the mux's Version is 3.0.

Directories

Path Synopsis
Package yaml converts JSON documents (the form produced by the OpenAPI emitters) to YAML.
Package yaml converts JSON documents (the form produced by the OpenAPI emitters) to YAML.

Jump to

Keyboard shortcuts

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