openapi

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package openapi generates OpenAPI 3.1 documents from Go request and response types, translating validate tags into JSON Schema constraints (min:3 on a string becomes minLength, in:a,b becomes enum, required populates the required list). Rules without a JSON Schema counterpart are skipped rather than approximated. A Generator accumulates operations and renders a Document or its JSON; DocsHTML serves a Scalar page for it.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidOption reports a nil option or an invalid option argument: an
	// empty title or version, a nil validator or schema, an empty tag, or an
	// empty response description.
	ErrInvalidOption = errors.New("openapi: invalid option")
	// ErrInvalidOperation reports an unusable Add call: an unknown method, a
	// relative path or one with a query or fragment, no response, a duplicate
	// response code, or a status outside 100..599.
	ErrInvalidOperation = errors.New("openapi: invalid operation")
	// ErrOperationExists reports an Add for a method and path already
	// registered.
	ErrOperationExists = errors.New("openapi: operation already exists")
)

Errors returned for invalid generator configuration and operations; they are wrapped, so match them with errors.Is.

Functions

func DocsHTML

func DocsHTML(title, specURL string) []byte

DocsHTML returns an HTML page that renders the OpenAPI document served at specURL with Scalar (https://github.com/scalar/scalar), loaded from the jsDelivr CDN. title and specURL are interpolated verbatim, so they must be trusted values, not user input.

Types

type Components

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

Components holds the named schemas referenced by $ref, one per named struct type reachable from the registered operations.

type Document

type Document struct {
	OpenAPI    string              `json:"openapi"`
	Info       Info                `json:"info"`
	Paths      map[string]PathItem `json:"paths,omitempty"`
	Components *Components         `json:"components,omitempty"`
}

Document is the generated OpenAPI 3.1 document, the subset of the specification the Generator emits. It marshals with encoding/json.

type Generator

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

Generator accumulates operations and the component schemas they reference. Schema names are allocated on first use and kept stable; distinct types that flatten to the same name get numeric suffixes. It is not safe for concurrent use.

func MustNew added in v0.2.1

func MustNew(title, version string, opts ...Option) *Generator

MustNew is New with panic-on-error semantics.

func New

func New(title, version string, opts ...Option) (*Generator, error)

New constructs a Generator for an API with the given title and version. Returns ErrInvalidOption when either is blank or an option fails.

func (*Generator) Add

func (g *Generator) Add[Request any](method, path string, opts ...OperationOption) error

Add registers an operation for method and path. Request describes the input: fields tagged uri become path parameters, fields tagged query become query parameters (required when their rules say so), and for POST, PUT and PATCH the remaining json-visible fields form the request body; use NoBody for none. At least one WithResponse or WithDefaultResponse option is required. Generation is transactional: on error, paths, components and schema-name allocation are unchanged.

Returns ErrInvalidOperation for a bad method, path or response set, ErrOperationExists when the method and path are already registered, ErrInvalidOption for a nil or failing option, and a wrapped error when a type's validate tags do not compile.

func (*Generator) Document

func (g *Generator) Document() Document

Document returns a deep copy of the document built so far, so callers can post-process it without affecting later Add calls.

func (*Generator) JSON

func (g *Generator) JSON() ([]byte, error)

JSON renders the document as indented JSON with sorted map keys, so the output is byte-stable across runs and suitable for committing.

type Info

type Info struct {
	Title   string `json:"title"`
	Version string `json:"version"`
}

Info identifies the API by the title and version given to New.

type MediaType

type MediaType struct {
	Schema *Schema `json:"schema,omitempty"`
}

MediaType associates a content type entry with its schema.

type NoBody added in v0.2.1

type NoBody struct{}

NoBody is the type argument for an operation without a JSON request body or for a response without content, such as 204.

type Operation

type Operation struct {
	Summary     string               `json:"summary,omitempty,omitzero"`
	Tags        []string             `json:"tags,omitempty"`
	Parameters  []*Parameter         `json:"parameters,omitempty"`
	RequestBody *RequestBody         `json:"requestBody,omitempty"`
	Responses   map[string]*Response `json:"responses"`
}

Operation describes one HTTP operation: its parameters, optional request body and responses keyed by status code or "default".

type OperationOption added in v0.2.1

type OperationOption func(*operationConfig) error

OperationOption configures one Add call.

func WithDefaultResponse added in v0.2.1

func WithDefaultResponse[Body any](opts ...ResponseOption) OperationOption

WithDefaultResponse adds the OpenAPI "default" response, used for any status not listed explicitly; Body follows the WithResponse rules.

func WithResponse added in v0.2.1

func WithResponse[Body any](status int, opts ...ResponseOption) OperationOption

WithResponse adds a response for an HTTP status whose JSON body is Body; use NoBody for a response without content. A status outside 100..599 or a code declared twice on one operation is ErrInvalidOperation at Add.

func WithSummary added in v0.2.1

func WithSummary(summary string) OperationOption

WithSummary sets the operation summary, trimmed of surrounding whitespace.

func WithTags added in v0.2.1

func WithTags(tags ...string) OperationOption

WithTags appends operation tags, trimmed; a blank tag is ErrInvalidOption.

type Option

type Option func(*Generator) error

Option configures a Generator during New; the first error aborts construction.

func WithSchema added in v0.2.1

func WithSchema[T any](schema *Schema) Option

WithSchema replaces the schema inferred for T (pointer layers ignored) wherever T appears, for types whose wire format reflection cannot see. The schema is deep-copied. A nil schema or T being NoBody is ErrInvalidOption.

func WithValidator

func WithValidator(v *validator.Validator) Option

WithValidator selects the Validator whose tag name, naming function and rule registry are used to inspect validate tags; the default is validator.Default. A nil v is ErrInvalidOption.

type Parameter

type Parameter struct {
	Name     string  `json:"name"`
	In       string  `json:"in"` // "path" or "query"
	Required bool    `json:"required,omitempty,omitzero"`
	Schema   *Schema `json:"schema,omitempty"`
}

Parameter describes a path or query parameter derived from a uri or query struct tag; path parameters are always required.

type PathItem

type PathItem map[string]*Operation

PathItem maps a lowercase HTTP method ("get", "post", ...) to its operation.

type RequestBody

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

RequestBody describes a JSON request body; Required is set when any body property is required.

type Response

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

Response describes one HTTP response; Content is nil for NoBody.

type ResponseOption added in v0.2.1

type ResponseOption func(*responseOptions) error

ResponseOption configures one WithResponse or WithDefaultResponse entry.

func ResponseDescription added in v0.2.1

func ResponseDescription(description string) ResponseOption

ResponseDescription overrides the response description, which defaults to the HTTP status text ("Created") or "Response" for the default response. A blank description is ErrInvalidOption.

type Schema

type Schema struct {
	Ref                  string             `json:"$ref,omitempty,omitzero"`
	Type                 string             `json:"type,omitempty,omitzero"`
	Format               string             `json:"format,omitempty,omitzero"`
	Description          string             `json:"description,omitempty,omitzero"`
	Properties           map[string]*Schema `json:"properties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	AdditionalProperties *Schema            `json:"additionalProperties,omitempty"`
	Required             []string           `json:"required,omitempty"`
	Enum                 []any              `json:"enum,omitempty"`
	Pattern              string             `json:"pattern,omitempty,omitzero"`
	Minimum              *float64           `json:"minimum,omitempty"`
	Maximum              *float64           `json:"maximum,omitempty"`
	ExclusiveMinimum     *float64           `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum     *float64           `json:"exclusiveMaximum,omitempty"`
	MinLength            *uint64            `json:"minLength,omitempty"`
	MaxLength            *uint64            `json:"maxLength,omitempty"`
	MinItems             *uint64            `json:"minItems,omitempty"`
	MaxItems             *uint64            `json:"maxItems,omitempty"`
	UniqueItems          bool               `json:"uniqueItems,omitempty,omitzero"`
	// ContentEncoding marks base64 payloads ([]byte fields), per JSON Schema 2020-12.
	ContentEncoding string `json:"contentEncoding,omitempty,omitzero"`
}

Schema is the JSON Schema subset used for parameters, bodies and components. Numeric bounds are pointers so that zero is distinguishable from unset.

Jump to

Keyboard shortcuts

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