Help us shape the future of Go! Take the 2026 Go Developer Survey

swagger

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 32 Imported by: 0

README

Arandu

Arandu Swagger

Arandu Swagger is the native OpenAPI integration for Arandu applications. It builds an OpenAPI 3.1.0 document from the route table that the application already owns, while request bodies, responses, examples, and security remain explicit beside each route.

The package is intentionally an Arandu module rather than a second framework:

  • it uses framework/http and the public Hesape route metadata;
  • it accepts native hesape/jsonschema schemas, and derives components from the Go types an application answers with;
  • its registry belongs to one swagger.Module instance;
  • it generates lazily after application boot and can cache serialized JSON;
  • its Swagger UI 5.32.14 assets are embedded and served from the same origin;
  • it has no database, migrations, service provider, container, discovery, mutable package registry, CDN, or runtime Node.js;
  • it adds openapi:export to the application's binary, which writes and checks the committed contract and is the only code that touches files;
  • documentation is disabled unless Config.Enabled is explicitly true.

Install

go get github.com/hyz-is/arandu-swagger

No migration or asset build follows installation.

Quick start

Create the documentation module in bootstrap/app.go:

docs, err := swagger.New(swagger.Config{
	Enabled:     cfg.App.Env == config.EnvDev,
	Title:       "Example API",
	Version:     "1.0.0",
	Description: "HTTP API documentation.",
	UIPath:      "/docs",
	SpecPath:    "/docs/openapi.json",
})
if err != nil {
	return App{}, err
}

Register shared native schemas and security schemes once:

schemas := map[string]jsonschema.Type{
	"User": jsonschema.Object(
		jsonschema.Prop("id", jsonschema.String().Format("uuid").Required()),
		jsonschema.Prop("name", jsonschema.String().Required()),
	),
	"CreateUser": jsonschema.Object(
		jsonschema.Prop("name", jsonschema.String().Required()),
	),
	"Problem": jsonschema.Object(
		jsonschema.Prop("message", jsonschema.String().Required()),
	),
}
for name, schema := range schemas {
	if err := docs.Schema(name, schema); err != nil {
		return App{}, err
	}
}
if err := docs.SecurityScheme("bearerAuth", swagger.HTTPBearer("JWT")); err != nil {
	return App{}, err
}

When a payload is a Go type the application already encodes, derive its component from the type instead of describing it a second time:

if err := docs.Models(
	swagger.ModelOf[resources.User]("User"),
	swagger.ModelOf[resources.Page[resources.User]]("UserPage"),
); err != nil {
	return App{}, err
}

A field is named by its json tag and required unless it is omitempty; a pointer is nullable, a type another model names is a $ref, and the doc, format and enum struct tags say what the type cannot. See Schemas and components.

When an existing OpenAPI contract uses Schema Object keywords outside the native Hesape builder set, import that individual schema through the validated JSON boundary and register its immutable snapshot:

databaseID, err := swagger.SchemaFromJSON([]byte(
	`{"type":"integer","format":"int64"}`,
))
if err != nil {
	return App{}, err
}
if err := docs.SchemaComponent("DatabaseID", databaseID); err != nil {
	return App{}, err
}

Pass only swagger.Documenter to an application module, then document its route at the declaration site:

route := r.Get("/api/users/{id}", http.HandlerFunc(m.show)).
	Name("users.show").
	WhereUuid("id")

m.docs.Route(route).
	Summary("Show a user").
	Description("Returns one user by UUID.").
	Tags("Users").
	PathParameter("id", swagger.Description("User identifier.")).
	Response(http.StatusOK, "User found", swagger.JSONRef("User")).
	Response(http.StatusNotFound, "User not found", swagger.JSONRef("Problem")).
	Security("bearerAuth")

Register Swagger last in the application's existing module list:

usersModule, err := users.New(users.Config{}, db, sessions, docs)
if err != nil {
	return App{}, err
}

app.Register(
	usersModule,
	billingModule,
	docs,
)

Registration remains explicit. foundation.Application calls Routes for each module during boot; Swagger captures that shared router and builds the document only on the first specification request. The complete compilable wiring is in examples/basic, and the public API snippets are compiled as Go examples in examples_test.go.

With the default paths, the module serves:

Method Path Purpose
GET /docs self-hosted Swagger UI
GET /docs/ permanent redirect to /docs
GET /docs/openapi.json OpenAPI 3.1.0 JSON
GET /docs/swagger-initializer.js CSP-safe UI initializer
GET /docs/theme.css generated theme stylesheet, registered with the UI even for the zero Theme
GET /docs/theme.js Theme.CustomJS, registered only when it is set
GET /docs/assets/5.32.14/* fixed, allowlisted UI assets

The UI and specification routes are not authenticated by this package. Attach application middleware through UIMiddleware and SpecMiddleware before enabling them outside a trusted development environment.

Committed contract

Registering the module adds openapi:export to the application's binary. It writes the document to docs/contracts/api.openapi.json (ContractDir and ContractName move it), and an application checks that the committed file still matches its route table with aru openapi:check, which runs the binary as openapi:export --check and fails naming each file that is missing or differs:

aru openapi:export   # write docs/contracts/api.openapi.json, then commit it
aru openapi:check    # in CI: fail when the committed contract is stale

The document is exported whenever Config.Title is set, also where Enabled is false, so documentation served only in development is still checked in CI. A route table that answers more than one contract declares the others with docs.Contract(registry, config), and openapi:export writes each one. No application keeps a cmd/openapi program: a contract no swagger.Module produces is a command of the application in app/Console/Commands, written with swagger.GenerateContract.

An exported document describes the HTTP surface alone. It is generated with GenerateContract, which leaves out the module each route is registered under (no x-arandu-module, and no tag taken from the module name), so moving routes between modules does not churn a committed file; the document served at /docs/openapi.json keeps both. Config.ContractServers lists the servers of the exported document in place of Servers, so a contract can name the production URL its SDKs call while the served document lists none and Swagger UI's "Try it out" calls the origin the page was loaded from. See Static generation and diagnostics.

Documentation model

By default, only routes passed to Documenter.Route are published. Arandu Swagger reliably infers the concrete HTTP method, full path, route name, path-parameter names, public constraints, module, domain metadata, and route deprecation metadata. It does not inspect handlers, execute requests, parse source code, or infer payloads and authorization.

The route name becomes operationId unless overridden. Every documented operation must declare at least one response with a non-empty description. Path parameters are always required in OpenAPI; missing declarations are added conservatively from the route metadata.

docs.Route(route).
	OperationID("users.store").
	QueryParameter("include", jsonschema.String().Enum("profile", "permissions"),
		swagger.Description("Relations to include."),
	).
	RequestBody(
		swagger.JSONRef("CreateUser").Required().
			Example(map[string]any{"name": "Ada"}),
	).
	Response(http.StatusCreated, "User created", swagger.JSONRef("User")).
	Response(http.StatusUnprocessableEntity, "Validation failed", swagger.JSONRef("Problem")).
	Security("bearerAuth")

See the focused guides for the complete surface:

Webhooks

The events an API sends to its consumers' endpoints are not routes, so the route table cannot describe them. Register them from the application's own catalogue of events -- the list a subscription is validated against -- and the document gains its OpenAPI 3.1 webhooks section, which Swagger UI shows beside the paths:

if err := docs.Models(swagger.ModelOf[resources.OrderEvent]("OrderEvent")); err != nil {
	return App{}, err
}

webhooks := make([]swagger.Webhook, 0, len(events.Names()))
for _, name := range events.Names() {
	webhooks = append(webhooks, swagger.Webhook{
		Name:        name, // "order.paid"
		OperationID: "webhooks:" + name,
		Summary:     "Sent when " + name + " happens.",
		Tags:        []string{"webhooks"},
		Body:        []*swagger.Media{swagger.JSONRef("OrderEvent")},
		Responses:   swagger.Responses{"2XX": {Description: "Received."}},
	})
}
if err := docs.Webhooks(webhooks...); err != nil {
	return App{}, err
}

Method defaults to POST, a declared body is required, and generation validates every reference and keeps webhook operationIds unique together with the routes'. Config.Filter selects routes only; it does not remove webhooks.

Programmatic generation

Generation does not require an HTTP server. The low-level API accepts the public route table, an instance-owned registry, and typed configuration:

registry := swagger.NewRegistry()
registry.Route(route).Response(http.StatusNoContent, "Service is healthy")

data, err := swagger.GenerateJSON(router.Routes(), registry, swagger.Config{
	Title:   "Example API",
	Version: "1.0.0",
})

These functions return bytes and never write them. A runnable example is in examples/static. The committed contract of an application is written by openapi:export (see Committed contract), not by a program of its own.

Routing boundaries

Route behavior Result
Named single-method route name is the automatic operationId
Unnamed route no operationId unless one is set explicitly
Match with concrete methods one operation per method; automatic IDs are method-qualified
ANY excluded when undocumented; documented use requires explicit Methods(...)
Explicit HEAD, OPTIONS, or TRACE represented
Implicit HEAD for a GET route not invented
Fallback, Swagger-owned, or hidden route always excluded
/_arandu route excluded unless IncludeInternal is true
Optional {id?} or multi-segment {path...} generation error
Unnormalized qualified binding such as {post:slug} generation error until Hesape supplies the cleaned {post} pattern
Generic Go regex not portable to ECMAScript generation error
Route domain preserved as x-arandu-domain, not treated as an enforced server

Constraints are preserved as string patterns when portable. Arandu Swagger does not narrow a route's runtime contract by guessing integer, UUID, ULID, or enum semantics from a pattern whose public metadata does not retain its source.

Production defaults

  • Keep Enabled environment-controlled. The zero configuration registers no endpoints.
  • Set CacheSpec: true after routes and documentation are immutable. Registry changes and route-table metadata changes invalidate the serialized cache safely.
  • Protect both UI and specification with application middleware. The package deliberately implements no authentication system.
  • Leave PersistAuthorization false unless the risk of browser-side token persistence is accepted.
  • Set DisableTryItOut when the documentation must remain read-only.
  • Use DisableUI: true for JSON-only service and CI deployments.
  • Use both DisableUI: true and DisableSpec: true for programmatic-only generation.

The dynamic HTML, initializer, and JSON responses use Cache-Control: no-store. Version-pinned embedded assets use an immutable one-year cache policy; their paths are not content-addressed. All served files are selected from a fixed allowlist and carry X-Content-Type-Options: nosniff.

Third-party material

The embedded Swagger UI distribution is Apache-2.0 licensed and pinned to version 5.32.14. Its license, notice, source, and file hashes are recorded in THIRD_PARTY.md. A project named Bolt Swagger informed the design, and no upstream for it could be verified, so its license and authorship are unknown. Nothing from it was copied: it is a design reference only, and docs/bolt-swagger.md records what that means.

Development

Run the same gates as CI with the enclosing Go workspace disabled:

export GOWORK=off
gofmt -l $(find . -name '*.go' -not -path '*/testdata/*' -not -name '*.kyse.go')
go build ./...
go vet ./...
go test -race ./...

See CONTRIBUTING.md before changing public behavior.

License

Arandu Swagger is MIT licensed. See LICENSE.md. Copyright (c) HYZIS - SERVICOS DIGITAIS LTDA - EPP.

Documentation

Overview

Package swagger generates and serves an OpenAPI document from the routes registered in an Arandu application.

Index

Examples

Constants

View Source
const (
	// DefaultUIPath is the documentation UI endpoint used when UIPath is empty.
	DefaultUIPath = "/docs"
	// DefaultSpecPath is the specification endpoint used when both UIPath and
	// SpecPath are empty.
	DefaultSpecPath = "/docs/openapi.json"
	// DefaultContractName is the document name openapi:export uses when
	// ContractName is empty.
	DefaultContractName = "api"
	// DefaultContractDir is the directory openapi:export writes to when
	// ContractDir is empty, relative to the working directory of the binary.
	DefaultContractDir = "docs/contracts"
)
View Source
const ExportCommandName = "openapi:export"

ExportCommandName is the console command the module adds to the application's binary. It writes every document the module exports to its contract file, and with --check compares each file with the generated document instead.

Variables

This section is empty.

Functions

func GenerateJSON

func GenerateJSON(routes []*fhttp.Route, registry *Registry, config Config) ([]byte, error)

GenerateJSON builds, validates, and deterministically serializes an OpenAPI document as JSON.

Example
package main

import (
	"fmt"
	"net/http"

	fhttp "github.com/arandu-io/framework/http"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	router := fhttp.NewRouter()
	registry := swagger.NewRegistry()
	route := router.Get("/health", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	}).Name("health.show")
	registry.Route(route).Response(http.StatusNoContent, "Service is healthy")

	data, err := swagger.GenerateJSON(router.Routes(), registry, swagger.Config{
		Title:   "Example API",
		Version: "1.0.0",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(len(data) > 0)
}
Output:
true

func PublishedPaths added in v0.4.0

func PublishedPaths() []string

PublishedPaths returns the files the module offers for publication.

func SchemasFromModels added in v0.4.8

func SchemasFromModels(models ...Model) (map[string]Schema, error)

SchemasFromModels derives the schema component of each model from its Go type, the way encoding/json writes a value of it:

  • a struct is an object whose properties are its exported fields, named and skipped by their json tags, in declaration order, with the fields of an embedded struct promoted as encoding/json promotes them. A field whose json tag carries neither omitempty nor omitzero is always written, so it is required;
  • string is string, bool is boolean, every integer kind is integer, float32 and float64 are number, and time.Time is a string of format date-time;
  • a slice or an array is an array of its element; a map with string keys is an object whose additionalProperties is its value; json.RawMessage and an interface accept any value;
  • a pointer is its element or null: ["string","null"] for a scalar, and anyOf the element and null for an object, an array or a reference;
  • a struct type that another model names is a $ref to that component wherever it appears below the root, and an unnamed struct is inlined.

Three struct tags describe a field beyond its type: doc is its description, format its format (date-time, uri, email, ...), and enum the values it takes, separated by commas -- integers for an integer field.

A type it cannot say -- a channel, a function, a complex number, a map with keys that are not strings, an inline struct that contains itself -- and a json tag option it does not follow, such as string, are errors naming the model and the field: a schema that guessed would describe something the encoder does not write.

A nil slice or map is written by encoding/json as null, and the schema says array or object: an application whose answers can carry one fills it, or declares the field as a pointer.

Every schema it returns passed the same validation SchemaFromJSON applies.

Example
package main

import (
	"encoding/json"
	"fmt"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	type Card struct {
		Brand string  `json:"brand"`
		Last4 *string `json:"last4"`
	}
	type PaymentMethod struct {
		ID   string `json:"id"`
		Type string `json:"type" enum:"card"`
		Card Card   `json:"card"`
		Note string `json:"note,omitempty" doc:"What the customer called it."`
	}

	schemas, err := swagger.SchemasFromModels(
		swagger.ModelOf[Card]("Card"),
		swagger.ModelOf[PaymentMethod]("PaymentMethod"),
	)
	if err != nil {
		panic(err)
	}
	encoded, _ := json.Marshal(schemas["PaymentMethod"])
	fmt.Println(string(encoded))
}
Output:
{"type":"object","required":["id","type","card"],"properties":{"id":{"type":"string"},"type":{"type":"string","enum":["card"]},"card":{"$ref":"#/components/schemas/Card"},"note":{"type":"string","description":"What the customer called it."}}}

Types

type APIKeyLocation

type APIKeyLocation string

APIKeyLocation identifies where an API key is carried in a request.

const (
	// APIKeyInQuery carries an API key in the URL query string.
	APIKeyInQuery APIKeyLocation = "query"
	// APIKeyInHeader carries an API key in an HTTP header.
	APIKeyInHeader APIKeyLocation = "header"
	// APIKeyInCookie carries an API key in an HTTP cookie.
	APIKeyInCookie APIKeyLocation = "cookie"
)

type Callback

type Callback map[string]*PathItem

Callback maps a runtime expression to the path item invoked by a callback.

type Components

type Components struct {
	// Schemas contains reusable Schema Objects.
	Schemas map[string]Schema `json:"schemas,omitempty"`
	// Responses contains reusable Response Objects.
	Responses map[string]*Response `json:"responses,omitempty"`
	// Parameters contains reusable Parameter Objects.
	Parameters map[string]*Parameter `json:"parameters,omitempty"`
	// Examples contains reusable Example Objects.
	Examples map[string]*Example `json:"examples,omitempty"`
	// RequestBodies contains reusable Request Body Objects.
	RequestBodies map[string]*RequestBody `json:"requestBodies,omitempty"`
	// Headers contains reusable Header Objects.
	Headers map[string]*Header `json:"headers,omitempty"`
	// SecuritySchemes contains reusable Security Scheme Objects.
	SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
	// Callbacks contains reusable Callback Objects.
	Callbacks map[string]Callback `json:"callbacks,omitempty"`
	// PathItems contains reusable Path Item Objects.
	PathItems map[string]*PathItem `json:"pathItems,omitempty"`
	// Extensions contains specification extensions for components.
	Extensions Extensions `json:"-"`
}

Components contains reusable OpenAPI objects keyed by component name.

func (Components) MarshalJSON

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

MarshalJSON renders the components and their specification extensions.

type Config

type Config struct {
	// Enabled registers the configured documentation endpoints when true.
	Enabled bool

	// Title is the API title written to the OpenAPI Info Object.
	Title string
	// Version is the documented API version written to the OpenAPI Info Object.
	Version string
	// Summary is the short API summary written to the OpenAPI Info Object.
	Summary string
	// Description is the API description written to the OpenAPI Info Object.
	Description string
	// TermsOfService is the API terms-of-service URL.
	TermsOfService string
	// Contact describes the API contact.
	Contact *Contact
	// License describes the API license.
	License *License
	// Servers lists the API server alternatives.
	Servers []Server
	// Tags declares the document-level tag metadata.
	Tags []Tag
	// ExternalDocs links to additional API documentation.
	ExternalDocs *ExternalDocumentation

	// JSONSchemaDialect overrides the default OpenAPI 3.1 schema dialect URI.
	// When empty, it defaults to "https://spec.openapis.org/oas/3.1/dialect/base".
	JSONSchemaDialect string

	// UIPath is the exact route serving the Swagger UI.
	UIPath string
	// SpecPath is the exact route serving the OpenAPI JSON document.
	SpecPath string
	// DisableUI prevents registration of the Swagger UI and its assets.
	DisableUI bool
	// DisableSpec prevents public registration of the OpenAPI JSON endpoint.
	// It requires DisableUI because the embedded UI consumes that endpoint.
	DisableSpec bool

	// IncludeUndocumented includes a basic operation for eligible routes that
	// were not explicitly registered with the Documenter.
	IncludeUndocumented bool
	// IncludeInternal allows internal Arandu routes to pass the default filter.
	IncludeInternal bool
	// Filter applies explicit route metadata and predicate filters.
	Filter RouteFilter

	// CacheSpec reuses serialized document bytes until registry or public route
	// metadata changes.
	CacheSpec bool
	// PersistAuthorization asks Swagger UI to retain authorization data.
	PersistAuthorization bool
	// DisableTryItOut removes interactive request execution from Swagger UI.
	DisableTryItOut bool

	// Locale specifies the UI language and localization (e.g. "pt-BR", "en").
	// When empty, it defaults to "en".
	Locale string
	// Translations supplies custom key-value translation mappings to override
	// or extend Swagger UI text strings.
	Translations map[string]string
	// ViewName specifies the Kyse view name rendered for the UI endpoint.
	// Defaults to "docs.swagger". If the view is not registered or fails to render,
	// the embedded standalone HTML shell is served as fallback.
	ViewName string

	// Theme configures visual styling, dark mode, colors, branding, and HTMX behavior.
	Theme Theme

	// ImageOrigins lists the exact HTTPS origins, such as
	// "https://cdn.example.com", beyond its own origin and data: URIs that the
	// UI page may load images from, for example an image in an API description.
	// The origin of an absolute Theme.Logo.URL or Theme.Favicon is admitted
	// without being listed here. Each entry is a scheme and host with an
	// optional port; a path, wildcard, or scheme other than https is rejected.
	ImageOrigins []string

	// UIMiddleware wraps the UI and embedded asset handlers in declaration order.
	UIMiddleware []Middleware
	// SpecMiddleware wraps the OpenAPI JSON handler in declaration order.
	SpecMiddleware []Middleware

	// ContractName names the committed document the openapi:export command
	// writes, as <ContractDir>/<ContractName>.openapi.json. It is one path
	// segment of letters, digits, dots, hyphens and underscores, and empty
	// means DefaultContractName.
	ContractName string
	// ContractDir is the directory openapi:export writes the document to and
	// openapi:export --check reads it from. A relative path is resolved
	// against the working directory of the binary, which is the application
	// root when aru runs it. Empty means DefaultContractDir.
	ContractDir string
	// ContractServers, when not empty, is the servers list of the document
	// openapi:export writes for this configuration, in place of Servers. The
	// document served over HTTP keeps Servers.
	//
	// It lets a committed contract name the production URL that SDKs are
	// generated against, such as "https://api.example.com", while the served
	// document lists no server, so that Swagger UI's "Try it out" sends its
	// requests to the origin the page was loaded from and a development
	// instance never calls production. Each entry is validated as Servers is.
	ContractServers []Server
}

Config controls document generation and the optional HTTP endpoints.

Documentation is opt-in: the zero value is disabled and valid. When Enabled is true, Title and Version identify the generated OpenAPI document. An empty UIPath defaults to DefaultUIPath. An empty SpecPath is placed below the effective UIPath as openapi.json.

func (Config) HasTheme added in v0.4.0

func (c Config) HasTheme() bool

HasTheme reports whether any visual styling, branding, or custom asset is configured.

func (Config) Validate

func (c Config) Validate() error

Validate reports configuration that cannot be served or generated safely. Dormant settings are ignored while Enabled is false so the zero value remains a complete opt-out switch.

type Contact

type Contact struct {
	// Name is the contact person's or organization's name.
	Name string `json:"name,omitempty"`
	// URL is a URL for the contact information.
	URL string `json:"url,omitempty"`
	// Email is the contact email address.
	Email string `json:"email,omitempty"`
	// Extensions contains specification extensions for the contact.
	Extensions Extensions `json:"-"`
}

Contact identifies a point of contact for the API.

func (Contact) MarshalJSON

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

MarshalJSON renders the contact and its specification extensions.

type Content

type Content map[string]*MediaType

Content maps media types to their schemas, examples, and encodings.

type Document

type Document struct {
	// OpenAPI is the semantic version of the OpenAPI specification.
	OpenAPI string `json:"openapi"`
	// Info contains API identification and ownership metadata.
	Info Info `json:"info"`
	// JSONSchemaDialect is the default dialect for Schema Objects.
	JSONSchemaDialect string `json:"jsonSchemaDialect,omitempty"`
	// Servers lists the target server alternatives for the API.
	Servers []Server `json:"servers,omitempty"`
	// Paths contains the API's HTTP operations.
	Paths Paths `json:"paths"`
	// Webhooks contains incoming operations initiated by the API provider.
	Webhooks Paths `json:"webhooks,omitempty"`
	// Components contains reusable OpenAPI objects.
	Components *Components `json:"components,omitempty"`
	// Security declares the default security requirements.
	Security []SecurityRequirement `json:"security,omitzero"`
	// Tags contains document-level metadata for operation tags.
	Tags []Tag `json:"tags,omitempty"`
	// ExternalDocs links to additional documentation for the API.
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
	// Extensions contains specification extensions for the document.
	Extensions Extensions `json:"-"`
}

Document is an OpenAPI 3.1 document.

func Generate

func Generate(routes []*fhttp.Route, registry *Registry, config Config) (*Document, error)

Generate builds and validates an OpenAPI 3.1 document from a route-table snapshot, an instance registry, and typed configuration. It does not start a server and is suitable for tests, CI, and static export by application code.

The document describes the application as it is composed: each operation carries the module its route is registered under as x-arandu-module, and an operation with no tags of its own is tagged with that module. This is the document the module serves. A committed contract is generated with GenerateContract instead.

func GenerateContract added in v0.6.0

func GenerateContract(routes []*fhttp.Route, registry *Registry, config Config) (*Document, error)

GenerateContract builds and validates the OpenAPI 3.1 document that openapi:export commits for the same route table, registry and configuration.

It differs from Generate in two ways, both so that the committed file describes the HTTP surface alone:

  • The module a route is registered under is left out. No operation carries x-arandu-module, and an operation with no tags of its own stays untagged instead of being tagged with its module. Which module registers a route is how the application is composed, and moving a route from one module to another changes no request or response. x-arandu-route-name, x-arandu-domain and the deprecation extensions remain.
  • When Config.ContractServers is not empty, it is the document's servers list in place of Config.Servers.

An application that writes a contract no swagger.Module exports, from a command of its own, generates it with this function so its bytes match what openapi:export would write.

Example
package main

import (
	"fmt"
	"net/http"

	fhttp "github.com/arandu-io/framework/http"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	router := fhttp.NewRouter().ForModule("billing")
	registry := swagger.NewRegistry()
	route := router.Get("/api/invoices", func(http.ResponseWriter, *http.Request) {}).Name("invoices.index")
	registry.Route(route).Response(http.StatusOK, "Invoices")
	config := swagger.Config{
		Title:           "Example API",
		Version:         "1.0.0",
		ContractServers: []swagger.Server{{URL: "https://api.example.com"}},
	}

	served, err := swagger.Generate(router.Routes(), registry, config)
	if err != nil {
		panic(err)
	}
	contract, err := swagger.GenerateContract(router.Routes(), registry, config)
	if err != nil {
		panic(err)
	}

	_, servedModule := served.Paths["/api/invoices"].Get.Extensions["x-arandu-module"]
	_, contractModule := contract.Paths["/api/invoices"].Get.Extensions["x-arandu-module"]
	fmt.Println(servedModule, len(served.Servers))
	fmt.Println(contractModule, contract.Servers[0].URL)
}
Output:
true 0
false https://api.example.com

func (Document) MarshalJSON

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

MarshalJSON renders the document and appends its specification extensions.

type Documenter

type Documenter interface {
	Route(route *fhttp.Route) *OperationBuilder
}

Documenter is the smallest contract an application module needs in order to document the routes it registers.

type Encoding

type Encoding struct {
	// ContentType is the media type for this property.
	ContentType string `json:"contentType,omitempty"`
	// Headers adds headers associated with this property's encoding.
	Headers map[string]*Header `json:"headers,omitempty"`
	// Style controls serialization of the property value.
	Style ParameterStyle `json:"style,omitempty"`
	// Explode controls serialization of composite property values.
	Explode *bool `json:"explode,omitempty"`
	// AllowReserved permits reserved URI characters in the encoded value.
	AllowReserved bool `json:"allowReserved,omitempty"`
	// Extensions contains specification extensions for the encoding.
	Extensions Extensions `json:"-"`
}

Encoding describes how one request-body property is serialized.

func (Encoding) MarshalJSON

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

MarshalJSON renders the property encoding and its specification extensions.

type Example

type Example struct {
	// Ref is a reference to a reusable Example Object.
	Ref string `json:"$ref,omitempty"`
	// Summary is a short description of the example.
	Summary string `json:"summary,omitempty"`
	// Description is the full example description.
	Description string `json:"description,omitempty"`
	// Value is the embedded example value.
	Value json.RawMessage `json:"value,omitempty"`
	// ExternalValue is a URL containing the example value.
	ExternalValue string `json:"externalValue,omitempty"`
	// Extensions contains specification extensions for the example.
	Extensions Extensions `json:"-"`
}

Example describes an example value, or references a reusable example component.

func (Example) MarshalJSON

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

MarshalJSON renders the example and its specification extensions.

type Extensions

type Extensions map[string]json.RawMessage

Extensions contains OpenAPI specification extensions keyed by an x- name. Values are raw JSON so an extension remains explicit without weakening the fixed OpenAPI objects to map[string]any.

type ExternalDocumentation

type ExternalDocumentation struct {
	// Description explains what the external documentation contains.
	Description string `json:"description,omitempty"`
	// URL is the target documentation URL.
	URL string `json:"url"`
	// Extensions contains specification extensions for the link.
	Extensions Extensions `json:"-"`
}

ExternalDocumentation links an OpenAPI object to further documentation.

func (ExternalDocumentation) MarshalJSON

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

MarshalJSON renders the external documentation and its extensions.

type HTMXConfig added in v0.4.0

type HTMXConfig struct {
	// Enabled adds HTMX lifecycle support to Swagger UI initialization.
	Enabled bool
	// Boost controls whether the Swagger UI container sets hx-boost="false"
	// to prevent HTMX from intercepting Swagger UI's internal buttons and forms.
	// When Enabled is true, Boost defaults to true.
	Boost bool
}

HTMXConfig configures HTMX compatibility behavior.

type Header struct {
	// Ref is a reference to a reusable Header Object.
	Ref string `json:"$ref,omitempty"`
	// Description explains the header's purpose.
	Description string `json:"description,omitempty"`
	// Required marks the header as mandatory.
	Required bool `json:"required,omitempty"`
	// Deprecated marks the header as deprecated.
	Deprecated bool `json:"deprecated,omitempty"`
	// Style controls serialization of the header value.
	Style ParameterStyle `json:"style,omitempty"`
	// Explode controls serialization of composite header values.
	Explode *bool `json:"explode,omitempty"`
	// Schema describes the header value.
	Schema *Schema `json:"schema,omitempty"`
	// Example is one example header value.
	Example json.RawMessage `json:"example,omitempty"`
	// Examples contains named header examples.
	Examples map[string]*Example `json:"examples,omitempty"`
	// Content describes a complex header using one media type.
	Content Content `json:"content,omitempty"`
	// Extensions contains specification extensions for the header.
	Extensions Extensions `json:"-"`
}

Header describes an HTTP response header, or references a reusable header component.

func (Header) MarshalJSON

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

MarshalJSON renders the header and its specification extensions.

type Info

type Info struct {
	// Title is the public API name.
	Title string `json:"title"`
	// Summary is a short description of the API.
	Summary string `json:"summary,omitempty"`
	// Description is the full API description.
	Description string `json:"description,omitempty"`
	// TermsOfService is the URL of the API terms of service.
	TermsOfService string `json:"termsOfService,omitempty"`
	// Contact identifies a point of contact for the API.
	Contact *Contact `json:"contact,omitempty"`
	// License identifies the API's license.
	License *License `json:"license,omitempty"`
	// Version is the documented API version.
	Version string `json:"version"`
	// Extensions contains specification extensions for the Info Object.
	Extensions Extensions `json:"-"`
}

Info describes the API exposed by an OpenAPI document.

func (Info) MarshalJSON

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

MarshalJSON renders the API information and its specification extensions.

type License

type License struct {
	// Name is the license name.
	Name string `json:"name"`
	// Identifier is the SPDX license expression.
	Identifier string `json:"identifier,omitempty"`
	// URL is a URL for the license text.
	URL string `json:"url,omitempty"`
	// Extensions contains specification extensions for the license.
	Extensions Extensions `json:"-"`
}

License identifies the license used by the API.

func (License) MarshalJSON

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

MarshalJSON renders the license and its specification extensions.

type Media

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

Media is one request or response representation supplied to a builder. Its schema and examples are immutable snapshots.

func JSON

func JSON(native jsonschema.Type) *Media

JSON returns an application/json representation using a native Hesape schema. Any snapshot failure is reported by generation with route context.

func JSONRef

func JSONRef(name string) *Media

JSONRef returns an application/json representation referencing a named schema component.

func MediaOf

func MediaOf(contentType string, native jsonschema.Type) *Media

MediaOf returns a representation with an explicit content type and native Hesape schema.

func MediaRef

func MediaRef(contentType, component string) *Media

MediaRef returns a representation with an explicit content type and schema component reference.

func MediaSchema added in v0.4.9

func MediaSchema(contentType string, schema Schema) *Media

MediaSchema returns a representation with an explicit content type and an already snapshotted schema, such as one SchemaFromJSON or SchemasFromModels returned. Use it when the schema needs keywords native Hesape builders cannot express, such as a $ref below the root.

func (*Media) Example

func (m *Media) Example(value any) *Media

Example snapshots one example value for this representation.

func (*Media) NamedExample

func (m *Media) NamedExample(name, summary, description string, value any) *Media

NamedExample snapshots a named example for this representation.

func (*Media) Required

func (m *Media) Required() *Media

Required marks this representation's request body required. If any representation is required, the containing request body is required.

type MediaType

type MediaType struct {
	// Schema describes values carried by this media type.
	Schema *Schema `json:"schema,omitempty"`
	// Example is one example media value.
	Example json.RawMessage `json:"example,omitempty"`
	// Examples contains named media examples.
	Examples map[string]*Example `json:"examples,omitempty"`
	// Encoding describes serialization of request-body properties.
	Encoding map[string]*Encoding `json:"encoding,omitempty"`
	// Extensions contains specification extensions for the media type.
	Extensions Extensions `json:"-"`
}

MediaType describes the representation carried by one content type.

func (MediaType) MarshalJSON

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

MarshalJSON renders the media type and its specification extensions.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware wraps one of the HTTP handlers exposed by the package.

type Model added in v0.4.8

type Model struct {
	Name string
	Type reflect.Type
}

Model names a Go type as a schema component: the name the document gives it, and the type whose values a response or a request carries.

A component derived from the type an application answers with is the contract and the answer at once. There is no second description of the payload to keep in step with the struct, which is the drift a hand-written schema invites: a field renamed in Go and not in the document is a client generated against a property the server stopped sending.

func ModelOf added in v0.4.8

func ModelOf[T any](name string) Model

ModelOf names T as the schema component name.

swagger.ModelOf[ProductResource]("Product")

type Module

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

Module is the Arandu module that owns one isolated documentation registry. It captures the application's shared router when Routes is called and generates the document lazily, after every application module has had an opportunity to register its routes.

func New

func New(cfg Config) (*Module, error)

New returns an independently configured Swagger module.

Example
package main

import (
	"fmt"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	docs, err := swagger.New(swagger.Config{
		Enabled:     true,
		Title:       "Example API",
		Version:     "1.0.0",
		Description: "HTTP API documentation.",
		UIPath:      "/docs",
		SpecPath:    "/docs/openapi.json",
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(docs.Name())
}
Output:
swagger

func (*Module) Commands added in v0.5.0

func (m *Module) Commands() []console.Command

Commands returns the openapi:export command, which the application's binary answers once the module is registered. It is empty when the module exports nothing: a configuration with no Title, such as the zero value, and no document declared through Contract.

openapi:export writes each document as indented JSON with a trailing newline, so the committed file is the same bytes on every run of the same route table. openapi:export --check writes nothing: it fails, naming each file, when a committed document is missing or differs from the generated one.

func (*Module) Contract added in v0.5.0

func (m *Module) Contract(registry *Registry, config Config) error

Contract declares another document that openapi:export writes beside the module's own. It is generated from the same route table the module captured, with registry as its documentation and config as its metadata and filter, and written to <config.ContractDir>/<config.ContractName>.openapi.json with the same defaults as the module's own document.

It serves an application whose route table answers more than one contract, such as a browser workspace and a public API: the module serves one document over HTTP, and the binary exports every one of them. Only the document fields of config are read; Enabled and the endpoint settings have no effect here.

Config is validated and snapshotted when Contract is called. Title and Version are required, and two documents may not share a file.

func (*Module) Diagnose

func (m *Module) Diagnose(context.Context) []string

Diagnose reports the most recent document generation failure.

func (*Module) ExampleComponent

func (m *Module) ExampleComponent(name string, example Example) error

ExampleComponent registers a reusable OpenAPI example component on this module instance.

func (*Module) Generate

func (m *Module) Generate() (*Document, error)

Generate builds the current typed OpenAPI document from the captured router.

func (*Module) GenerateJSON

func (m *Module) GenerateJSON() ([]byte, error)

GenerateJSON serializes the current OpenAPI document. When CacheSpec is enabled it shares the registry- and route-aware cache used by the HTTP endpoint.

func (*Module) Header

func (m *Module) Header(name string, header Header) error

Header registers a reusable OpenAPI header component on this module instance.

func (*Module) Models added in v0.4.8

func (m *Module) Models(models ...Model) error

Models registers the schema components derived from the models' Go types on this module instance.

func (*Module) Name

func (m *Module) Name() string

Name returns the stable module identifier.

func (*Module) Parameter

func (m *Module) Parameter(name string, parameter Parameter) error

Parameter registers a reusable OpenAPI parameter component on this module instance.

func (*Module) Publishes added in v0.4.0

func (m *Module) Publishes() []foundation.Publication

Publishes declares the files this package offers, each at the path it takes relative to the root of the project.

func (*Module) RequestBody

func (m *Module) RequestBody(name string, body RequestBody) error

RequestBody registers a reusable OpenAPI request-body component on this module instance.

func (*Module) Response

func (m *Module) Response(name string, response Response) error

Response registers a reusable OpenAPI response component on this module instance.

func (*Module) Route

func (m *Module) Route(route *fhttp.Route) *OperationBuilder

Route returns the operation builder associated with an application route.

Example
package main

import (
	"fmt"
	"net/http"

	fhttp "github.com/arandu-io/framework/http"
	"github.com/arandu-io/hesape/jsonschema"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	docs, err := swagger.New(swagger.Config{
		Enabled: true,
		Title:   "Example API",
		Version: "1.0.0",
	})
	if err != nil {
		panic(err)
	}
	if err := docs.Schema("User", jsonschema.Object(
		jsonschema.Prop("id", jsonschema.String().Format("uuid").Required()),
	)); err != nil {
		panic(err)
	}
	if err := docs.SecurityScheme("bearerAuth", swagger.HTTPBearer("JWT")); err != nil {
		panic(err)
	}

	router := fhttp.NewRouter().ForModule("users")
	route := router.Get("/api/users/{id}", func(http.ResponseWriter, *http.Request) {}).
		Name("users.show").
		WhereUuid("id")
	docs.Route(route).
		Summary("Show a user").
		Tags("Users").
		PathParameter("id", swagger.Description("User identifier.")).
		Response(http.StatusOK, "User found", swagger.JSONRef("User")).
		Security("bearerAuth")
	docs.Routes(router.ForModule(docs.Name()))

	document, err := docs.Generate()
	if err != nil {
		panic(err)
	}
	fmt.Println(document.OpenAPI, document.Paths["/api/users/{id}"].Get.OperationID)
}
Output:
3.1.0 users.show

func (*Module) Routes

func (m *Module) Routes(router *fhttp.Router)

Routes captures the shared application router and registers the enabled specification and self-hosted UI endpoints.

func (*Module) Schema

func (m *Module) Schema(name string, schema jsonschema.Type) error

Schema registers a reusable native Hesape JSON Schema component on this module instance.

func (*Module) SchemaComponent

func (m *Module) SchemaComponent(name string, schema Schema) error

SchemaComponent registers an already snapshotted OpenAPI schema component on this module instance.

func (*Module) SecurityScheme

func (m *Module) SecurityScheme(name string, scheme SecurityScheme) error

SecurityScheme registers a reusable OpenAPI security scheme component on this module instance.

func (*Module) Webhooks added in v0.4.9

func (m *Module) Webhooks(webhooks ...Webhook) error

Webhooks registers webhooks on this module instance. See Registry.Webhooks.

Example
package main

import (
	"fmt"

	fhttp "github.com/arandu-io/framework/http"

	swagger "github.com/hyz-is/arandu-swagger"
)

func main() {
	type Order struct {
		ID          string `json:"id"`
		AmountCents int64  `json:"amount_cents"`
	}
	type OrderEvent struct {
		ID   string `json:"id"`
		Type string `json:"type"`
		Data Order  `json:"data"`
	}

	docs, err := swagger.New(swagger.Config{
		Enabled: true,
		Title:   "Example API",
		Version: "1.0.0",
	})
	if err != nil {
		panic(err)
	}
	if err := docs.Models(swagger.ModelOf[Order]("Order"), swagger.ModelOf[OrderEvent]("OrderEvent")); err != nil {
		panic(err)
	}

	// The application's catalogue of the events it sends.
	events := []string{"order.created", "order.paid"}
	webhooks := make([]swagger.Webhook, 0, len(events))
	for _, name := range events {
		webhooks = append(webhooks, swagger.Webhook{
			Name:        name,
			OperationID: "webhooks:" + name,
			Summary:     "Sent when " + name + " happens.",
			Body:        []*swagger.Media{swagger.JSONRef("OrderEvent")},
			Responses:   swagger.Responses{"2XX": {Description: "Received."}},
		})
	}
	if err := docs.Webhooks(webhooks...); err != nil {
		panic(err)
	}
	docs.Routes(fhttp.NewRouter().ForModule(docs.Name()))

	document, err := docs.Generate()
	if err != nil {
		panic(err)
	}
	fmt.Println(len(document.Webhooks), document.Webhooks["order.paid"].Post.OperationID)
}
Output:
2 webhooks:order.paid

type OAuthFlow

type OAuthFlow struct {
	// AuthorizationURL is the endpoint where a user grants authorization.
	AuthorizationURL string `json:"authorizationUrl,omitempty"`
	// TokenURL is the endpoint used to obtain tokens.
	TokenURL string `json:"tokenUrl,omitempty"`
	// RefreshURL is the endpoint used to refresh tokens.
	RefreshURL string `json:"refreshUrl,omitempty"`
	// Scopes maps OAuth scope names to their descriptions.
	Scopes map[string]string `json:"scopes"`
	// Extensions contains specification extensions for the flow.
	Extensions Extensions `json:"-"`
}

OAuthFlow describes the endpoints and scopes for one OAuth 2.0 flow.

func (OAuthFlow) MarshalJSON

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

MarshalJSON renders the OAuth flow and its specification extensions.

type OAuthFlows

type OAuthFlows struct {
	// Implicit describes an OAuth 2.0 implicit flow.
	Implicit *OAuthFlow `json:"implicit,omitempty"`
	// Password describes an OAuth 2.0 resource owner password flow.
	Password *OAuthFlow `json:"password,omitempty"`
	// ClientCredentials describes an OAuth 2.0 client credentials flow.
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	// AuthorizationCode describes an OAuth 2.0 authorization code flow.
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
	// Extensions contains specification extensions for the flow collection.
	Extensions Extensions `json:"-"`
}

OAuthFlows contains the OAuth 2.0 flows supported by a security scheme.

func (OAuthFlows) MarshalJSON

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

MarshalJSON renders the OAuth flows and their specification extensions.

type Operation

type Operation struct {
	// Tags groups the operation for readers and tooling.
	Tags []string `json:"tags,omitempty"`
	// Summary is a short description of the operation.
	Summary string `json:"summary,omitempty"`
	// Description is the full operation description.
	Description string `json:"description,omitempty"`
	// ExternalDocs links to additional operation documentation.
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
	// OperationID uniquely identifies the operation in this document.
	OperationID string `json:"operationId,omitempty"`
	// Parameters contains path, query, header, and cookie parameters.
	Parameters []*Parameter `json:"parameters,omitempty"`
	// RequestBody describes the optional request body.
	RequestBody *RequestBody `json:"requestBody,omitempty"`
	// Responses contains the operation's possible responses.
	Responses Responses `json:"responses"`
	// Callbacks contains callbacks initiated by this operation.
	Callbacks map[string]Callback `json:"callbacks,omitempty"`
	// Deprecated marks the operation as deprecated.
	Deprecated bool `json:"deprecated,omitempty"`
	// Security overrides the document security requirements.
	Security []SecurityRequirement `json:"security,omitzero"`
	// Servers overrides the document servers for this operation.
	Servers []Server `json:"servers,omitempty"`
	// Extensions contains specification extensions for the operation.
	Extensions Extensions `json:"-"`
}

Operation describes one HTTP operation on a path.

func (Operation) MarshalJSON

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

MarshalJSON renders the operation and its specification extensions.

type OperationBuilder

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

OperationBuilder documents one registered route. Its methods are safe to call concurrently, although normal applications use it only during boot.

func (*OperationBuilder) CookieParameter

func (b *OperationBuilder) CookieParameter(name string, schema jsonschema.Type, options ...ParameterOption) *OperationBuilder

CookieParameter documents a cookie parameter with a native schema.

func (*OperationBuilder) DefaultResponse

func (b *OperationBuilder) DefaultResponse(description string, media ...*Media) *OperationBuilder

DefaultResponse declares the operation's default response.

func (*OperationBuilder) Deprecated

func (b *OperationBuilder) Deprecated() *OperationBuilder

Deprecated marks the operation deprecated even when the route itself has no deprecation dates.

func (*OperationBuilder) Description

func (b *OperationBuilder) Description(description string) *OperationBuilder

Description sets the operation's long description.

func (*OperationBuilder) Extension

func (b *OperationBuilder) Extension(name string, value any) *OperationBuilder

Extension sets an x-* operation extension after snapshotting its JSON value.

func (*OperationBuilder) ExternalDocumentation

func (b *OperationBuilder) ExternalDocumentation(docs ExternalDocumentation) *OperationBuilder

ExternalDocumentation attaches further documentation to the operation.

func (*OperationBuilder) HeaderParameter

func (b *OperationBuilder) HeaderParameter(name string, schema jsonschema.Type, options ...ParameterOption) *OperationBuilder

HeaderParameter documents a request-header parameter with a native schema.

func (*OperationBuilder) Hidden

func (b *OperationBuilder) Hidden() *OperationBuilder

Hidden excludes the operation from every generated document.

func (*OperationBuilder) Ignore

func (b *OperationBuilder) Ignore() *OperationBuilder

Ignore is an alias for Hidden.

func (*OperationBuilder) Methods

func (b *OperationBuilder) Methods(methods ...string) *OperationBuilder

Methods explicitly maps an ANY route, or a subset of a multi-method route, to concrete OpenAPI methods.

func (*OperationBuilder) OperationID

func (b *OperationBuilder) OperationID(id string) *OperationBuilder

OperationID sets the operation identifier for a single-method route. Multi-method routes should use OperationIDFor or automatic method-qualified identifiers.

func (*OperationBuilder) OperationIDFor

func (b *OperationBuilder) OperationIDFor(method, id string) *OperationBuilder

OperationIDFor sets the operation identifier for one concrete HTTP method of a multi-method route.

func (*OperationBuilder) ParameterRef

func (b *OperationBuilder) ParameterRef(name string) *OperationBuilder

ParameterRef adds a reference to a reusable parameter component.

func (*OperationBuilder) PathParameter

func (b *OperationBuilder) PathParameter(name string, options ...ParameterOption) *OperationBuilder

PathParameter documents a parameter already present in the route path.

func (*OperationBuilder) QueryParameter

func (b *OperationBuilder) QueryParameter(name string, schema jsonschema.Type, options ...ParameterOption) *OperationBuilder

QueryParameter documents a query-string parameter with a native schema.

func (*OperationBuilder) RequestBody

func (b *OperationBuilder) RequestBody(media ...*Media) *OperationBuilder

RequestBody sets the operation request body from one or more media types.

func (*OperationBuilder) RequestBodyDescription

func (b *OperationBuilder) RequestBodyDescription(description string) *OperationBuilder

RequestBodyDescription sets the request body description, creating an empty body draft when necessary so generation can report missing content clearly.

func (*OperationBuilder) RequestBodyRef

func (b *OperationBuilder) RequestBodyRef(component string) *OperationBuilder

RequestBodyRef sets the operation request body to a reusable request-body component.

func (*OperationBuilder) Response

func (b *OperationBuilder) Response(status int, description string, media ...*Media) *OperationBuilder

Response declares a concrete HTTP status response.

func (*OperationBuilder) ResponseHeader

func (b *OperationBuilder) ResponseHeader(status int, name string, header Header) *OperationBuilder

ResponseHeader adds a header to a previously declared response. It may be called first; generation then reports a missing response description.

func (*OperationBuilder) ResponseRef

func (b *OperationBuilder) ResponseRef(status int, component string) *OperationBuilder

ResponseRef declares a response that references a reusable response component.

func (*OperationBuilder) Security

func (b *OperationBuilder) Security(name string, scopes ...string) *OperationBuilder

Security adds one alternative security requirement. Calling it more than once creates OpenAPI OR alternatives; pass multiple schemes to SecurityAll for an AND requirement.

func (*OperationBuilder) SecurityAll

func (b *OperationBuilder) SecurityAll(requirement SecurityRequirement) *OperationBuilder

SecurityAll adds one security requirement containing every supplied scheme.

func (*OperationBuilder) Summary

func (b *OperationBuilder) Summary(summary string) *OperationBuilder

Summary sets the operation's short summary.

func (*OperationBuilder) Tags

func (b *OperationBuilder) Tags(tags ...string) *OperationBuilder

Tags replaces the operation's explicit tags.

type Parameter

type Parameter struct {
	// Ref is a reference to a reusable Parameter Object.
	Ref string `json:"$ref,omitempty"`
	// Name is the case-sensitive parameter name.
	Name string `json:"name,omitempty"`
	// In identifies the request location carrying the parameter.
	In ParameterLocation `json:"in,omitempty"`
	// Description explains the parameter's purpose.
	Description string `json:"description,omitempty"`
	// Required marks a parameter as mandatory.
	Required bool `json:"required,omitempty"`
	// Deprecated marks the parameter as deprecated.
	Deprecated bool `json:"deprecated,omitempty"`
	// AllowEmptyValue permits an empty query parameter value.
	AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
	// Style controls serialization of the parameter value.
	Style ParameterStyle `json:"style,omitempty"`
	// Explode controls whether composite values use separate parameters.
	Explode *bool `json:"explode,omitempty"`
	// AllowReserved permits reserved URI characters in a query value.
	AllowReserved bool `json:"allowReserved,omitempty"`
	// Schema describes the parameter value.
	Schema *Schema `json:"schema,omitempty"`
	// Example is one example parameter value.
	Example json.RawMessage `json:"example,omitempty"`
	// Examples contains named parameter examples.
	Examples map[string]*Example `json:"examples,omitempty"`
	// Content describes a complex parameter using one media type.
	Content Content `json:"content,omitempty"`
	// Extensions contains specification extensions for the parameter.
	Extensions Extensions `json:"-"`
}

Parameter describes one operation or path parameter, or references a reusable parameter component.

func (Parameter) MarshalJSON

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

MarshalJSON renders the parameter and its specification extensions.

type ParameterLocation

type ParameterLocation string

ParameterLocation is the part of a request that carries a parameter.

const (
	// ParameterInQuery places a parameter in the URL query string.
	ParameterInQuery ParameterLocation = "query"
	// ParameterInHeader places a parameter in an HTTP header.
	ParameterInHeader ParameterLocation = "header"
	// ParameterInPath places a parameter in the URL path template.
	ParameterInPath ParameterLocation = "path"
	// ParameterInCookie places a parameter in an HTTP cookie.
	ParameterInCookie ParameterLocation = "cookie"
)

type ParameterOption

type ParameterOption func(*parameterSettings) error

ParameterOption changes an explicitly documented operation parameter.

func Description

func Description(description string) ParameterOption

Description returns an option that describes a parameter.

func ExampleValue

func ExampleValue(value any) ParameterOption

ExampleValue returns an option that snapshots one parameter example.

func ParameterDeprecated

func ParameterDeprecated() ParameterOption

ParameterDeprecated returns an option that marks a parameter deprecated.

func ParameterRequired

func ParameterRequired() ParameterOption

ParameterRequired returns an option that marks a non-path parameter as required. Path parameters are always required regardless of this option.

func ParameterSchema

func ParameterSchema(native jsonschema.Type) ParameterOption

ParameterSchema returns an option that uses a native Hesape schema.

func ParameterSchemaRef

func ParameterSchemaRef(name string) ParameterOption

ParameterSchemaRef returns an option that references a reusable schema.

type ParameterStyle

type ParameterStyle string

ParameterStyle controls how a parameter is serialized.

const (
	// ParameterStyleMatrix uses semicolon-prefixed path parameters.
	ParameterStyleMatrix ParameterStyle = "matrix"
	// ParameterStyleLabel uses dot-prefixed path parameters.
	ParameterStyleLabel ParameterStyle = "label"
	// ParameterStyleForm uses conventional query or cookie serialization.
	ParameterStyleForm ParameterStyle = "form"
	// ParameterStyleSimple uses comma-separated path or header serialization.
	ParameterStyleSimple ParameterStyle = "simple"
	// ParameterStyleSpaceDelimited uses space-delimited array values.
	ParameterStyleSpaceDelimited ParameterStyle = "spaceDelimited"
	// ParameterStylePipeDelimited uses pipe-delimited array values.
	ParameterStylePipeDelimited ParameterStyle = "pipeDelimited"
	// ParameterStyleDeepObject uses bracketed query object properties.
	ParameterStyleDeepObject ParameterStyle = "deepObject"
)

type PathItem

type PathItem struct {
	// Ref is a reference to a reusable Path Item Object.
	Ref string `json:"$ref,omitempty"`
	// Summary describes every operation on this path.
	Summary string `json:"summary,omitempty"`
	// Description explains every operation on this path.
	Description string `json:"description,omitempty"`
	// Get is the HTTP GET operation.
	Get *Operation `json:"get,omitempty"`
	// Put is the HTTP PUT operation.
	Put *Operation `json:"put,omitempty"`
	// Post is the HTTP POST operation.
	Post *Operation `json:"post,omitempty"`
	// Delete is the HTTP DELETE operation.
	Delete *Operation `json:"delete,omitempty"`
	// Options is the HTTP OPTIONS operation.
	Options *Operation `json:"options,omitempty"`
	// Head is the HTTP HEAD operation.
	Head *Operation `json:"head,omitempty"`
	// Patch is the HTTP PATCH operation.
	Patch *Operation `json:"patch,omitempty"`
	// Trace is the HTTP TRACE operation.
	Trace *Operation `json:"trace,omitempty"`
	// Servers overrides the document servers for this path.
	Servers []Server `json:"servers,omitempty"`
	// Parameters applies parameters to every operation on this path.
	Parameters []*Parameter `json:"parameters,omitempty"`
	// Extensions contains specification extensions for the path item.
	Extensions Extensions `json:"-"`
}

PathItem describes the operations available at one path.

func (PathItem) MarshalJSON

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

MarshalJSON renders the path item and its specification extensions.

type Paths

type Paths map[string]*PathItem

Paths maps absolute API paths to their operations.

type Reference

type Reference struct {
	// Ref is the reference URI.
	Ref string `json:"$ref"`
	// Summary overrides the referenced object's summary where supported.
	Summary string `json:"summary,omitempty"`
	// Description overrides the referenced object's description where supported.
	Description string `json:"description,omitempty"`
	// Extensions contains specification extensions for the reference.
	Extensions Extensions `json:"-"`
}

Reference points to an OpenAPI component or another resolvable object.

func (Reference) MarshalJSON

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

MarshalJSON renders the reference and its specification extensions.

type Registry

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

Registry owns the route documentation and reusable OpenAPI components for one Swagger module instance.

A Registry is safe for concurrent registration and generation. Builders and native schemas are snapshotted at their registration boundary; callers must still finish mutating a Hesape route before the application starts serving.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty, instance-owned documentation registry.

func (*Registry) ExampleComponent

func (r *Registry) ExampleComponent(name string, example Example) error

ExampleComponent registers a named reusable OpenAPI example.

func (*Registry) Header

func (r *Registry) Header(name string, header Header) error

Header registers a named reusable OpenAPI response header.

func (*Registry) Models added in v0.4.8

func (r *Registry) Models(models ...Model) error

Models registers the schema component SchemasFromModels derives from each model's Go type. Nothing is registered when any of them cannot be derived.

func (*Registry) Parameter

func (r *Registry) Parameter(name string, parameter Parameter) error

Parameter registers a named reusable OpenAPI parameter.

func (*Registry) RequestBody

func (r *Registry) RequestBody(name string, body RequestBody) error

RequestBody registers a named reusable OpenAPI request body.

func (*Registry) Response

func (r *Registry) Response(name string, response Response) error

Response registers a named reusable OpenAPI response.

func (*Registry) Revision

func (r *Registry) Revision() uint64

Revision returns the registry revision used to invalidate a generated document cache. Every successful mutation and every recorded error advances it.

func (*Registry) Route

func (r *Registry) Route(route *fhttp.Route) *OperationBuilder

Route returns the fluent documentation builder associated with route. Calling Route twice for the same pointer continues the same operation draft.

func (*Registry) Schema

func (r *Registry) Schema(name string, native jsonschema.Type) error

Schema registers a named reusable native Hesape JSON Schema snapshot. Repeating the same component is idempotent; changing its content is an error.

func (*Registry) SchemaComponent

func (r *Registry) SchemaComponent(name string, schema Schema) error

SchemaComponent registers an already snapshotted OpenAPI schema. Use SchemaFromJSON to import keywords that native Hesape builders cannot express.

func (*Registry) SecurityScheme

func (r *Registry) SecurityScheme(name string, scheme SecurityScheme) error

SecurityScheme registers a named reusable OpenAPI security scheme.

func (*Registry) Webhooks added in v0.4.9

func (r *Registry) Webhooks(webhooks ...Webhook) error

Webhooks registers webhooks the generated document lists under its OpenAPI 3.1 webhooks section. Registering the same webhook again with the same content is idempotent; a different webhook under the same name and method is an error. Nothing is registered when any of them is invalid.

References to components -- a JSONRef body, a ParameterRef-style parameter, a security scheme -- are resolved and validated by generation, together with the operationId uniqueness the webhooks share with the routes.

type RequestBody

type RequestBody struct {
	// Ref is a reference to a reusable Request Body Object.
	Ref string `json:"$ref,omitempty"`
	// Description explains the request body.
	Description string `json:"description,omitempty"`
	// Content maps accepted media types to their representations.
	Content Content `json:"content,omitempty"`
	// Required marks the request body as mandatory.
	Required bool `json:"required,omitempty"`
	// Extensions contains specification extensions for the request body.
	Extensions Extensions `json:"-"`
}

RequestBody describes the body of a request, or references a reusable request body component.

func (RequestBody) MarshalJSON

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

MarshalJSON renders the request body and its specification extensions.

type Response

type Response struct {
	// Ref is a reference to a reusable Response Object.
	Ref string `json:"$ref,omitempty"`
	// Description explains the response.
	Description string `json:"description,omitempty"`
	// Headers contains response header metadata.
	Headers map[string]*Header `json:"headers,omitempty"`
	// Content maps returned media types to their representations.
	Content Content `json:"content,omitempty"`
	// Extensions contains specification extensions for the response.
	Extensions Extensions `json:"-"`
}

Response describes an operation response, or references a reusable response component.

func (Response) MarshalJSON

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

MarshalJSON renders the response and its specification extensions.

type Responses

type Responses map[string]*Response

Responses maps HTTP status codes or default to operation responses.

type RouteFilter

type RouteFilter struct {
	// IncludePrefixes allows routes whose paths start with one of these values.
	IncludePrefixes []string
	// ExcludePrefixes rejects routes whose paths start with one of these values.
	ExcludePrefixes []string
	// IncludeNames allows routes with one of these route names.
	IncludeNames []string
	// ExcludeNames rejects routes with one of these route names.
	ExcludeNames []string
	// IncludeModules allows routes owned by one of these module names.
	IncludeModules []string
	// ExcludeModules rejects routes owned by one of these module names.
	ExcludeModules []string
	// IncludeMethods allows routes using one of these HTTP methods.
	IncludeMethods []string
	// ExcludeMethods rejects routes using one of these HTTP methods.
	ExcludeMethods []string
	// IncludeDomains allows routes scoped to one of these domains.
	IncludeDomains []string
	// ExcludeDomains rejects routes scoped to one of these domains.
	ExcludeDomains []string
	// IncludePredicate applies an additional caller-defined allow rule.
	IncludePredicate RoutePredicate
	// ExcludePredicate applies an additional caller-defined deny rule.
	ExcludePredicate RoutePredicate
}

RouteFilter limits which application routes may appear in the document.

A non-empty include list acts as an allowlist for that dimension. Exclusions are applied after inclusions. Prefixes match route paths; all other list fields match their route metadata. IncludePredicate must accept a route and ExcludePredicate must not reject it.

type RoutePredicate

type RoutePredicate func(*frameworkhttp.Route) bool

RoutePredicate decides whether a route passes a caller-defined filter.

type Schema

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

Schema is an immutable OpenAPI schema snapshot or a schema reference. Native schema builders are snapshotted by SchemaFrom so later builder mutations cannot race with or alter document generation.

func SchemaFrom

func SchemaFrom(native jsonschema.Type) (schema Schema, err error)

SchemaFrom snapshots a native Hesape JSON Schema type for use in OpenAPI. It returns an error when the type is nil, panics while marshaling, or does not produce a structurally valid JSON Schema object supported by this adapter.

func SchemaFromJSON

func SchemaFromJSON(encoded []byte) (Schema, error)

SchemaFromJSON validates and snapshots one JSON-encoded OpenAPI Schema Object. Native Hesape builders remain the preferred construction path; this import boundary preserves schema keywords that their closed type set cannot represent.

func SchemaRef

func SchemaRef(name string) Schema

SchemaRef returns a local reference to a named schema component.

func SchemaReference

func SchemaReference(reference string) Schema

SchemaReference returns a schema that uses the exact reference supplied by the caller. Its URI-reference syntax is checked when marshaled and during document generation.

func (Schema) IsReference

func (s Schema) IsReference() bool

IsReference reports whether the schema is represented by a reference.

func (Schema) IsZero

func (s Schema) IsZero() bool

IsZero reports whether the schema contains neither a snapshot nor a reference.

func (Schema) JSON

func (s Schema) JSON() json.RawMessage

JSON returns a copy of an inline schema snapshot. It returns nil for a reference or an empty schema.

func (Schema) MarshalJSON

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

MarshalJSON renders the immutable schema snapshot or reference.

func (Schema) Reference

func (s Schema) Reference() string

Reference returns the schema reference, or an empty string for an inline schema snapshot.

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement maps a security scheme name to the scopes required from that scheme. An empty scope list is used by non-OAuth schemes.

func SecurityRequirementFor

func SecurityRequirementFor(name string, scopes ...string) SecurityRequirement

SecurityRequirementFor builds one requirement for a named security scheme.

func (SecurityRequirement) MarshalJSON

func (r SecurityRequirement) MarshalJSON() ([]byte, error)

MarshalJSON renders absent scopes as an empty JSON array, which is the OpenAPI representation required for non-OAuth security schemes.

type SecurityScheme

type SecurityScheme struct {
	// Ref is a reference to a reusable Security Scheme Object.
	Ref string `json:"$ref,omitempty"`
	// Type identifies the security scheme kind.
	Type SecuritySchemeType `json:"type,omitempty"`
	// Description explains how the security scheme is used.
	Description string `json:"description,omitempty"`
	// Name is the request value carrying an API key.
	Name string `json:"name,omitempty"`
	// In is the request location carrying an API key.
	In APIKeyLocation `json:"in,omitempty"`
	// Scheme is the HTTP Authorization scheme name.
	Scheme string `json:"scheme,omitempty"`
	// BearerFormat is a documentation hint for bearer token formatting.
	BearerFormat string `json:"bearerFormat,omitempty"`
	// Flows contains the supported OAuth 2.0 flows.
	Flows *OAuthFlows `json:"flows,omitempty"`
	// OpenIDConnectURL is the OpenID Connect discovery URL.
	OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
	// Extensions contains specification extensions for the security scheme.
	Extensions Extensions `json:"-"`
}

SecurityScheme describes an authentication mechanism, or references a reusable security scheme component.

func APIKey

func APIKey(name string, location APIKeyLocation) SecurityScheme

APIKey builds a security scheme for an API key in a query, header, or cookie value.

func HTTPBasic

func HTTPBasic() SecurityScheme

HTTPBasic builds an HTTP Basic authentication security scheme.

func HTTPBearer

func HTTPBearer(format string) SecurityScheme

HTTPBearer builds an HTTP bearer security scheme.

func MutualTLS

func MutualTLS() SecurityScheme

MutualTLS builds a mutual TLS security scheme.

func OAuth2

func OAuth2(flows OAuthFlows) SecurityScheme

OAuth2 builds an OAuth 2.0 security scheme from its supported flows.

func OpenIDConnect

func OpenIDConnect(discoveryURL string) SecurityScheme

OpenIDConnect builds an OpenID Connect security scheme from its discovery URL.

func SecuritySchemeRef

func SecuritySchemeRef(name string) SecurityScheme

SecuritySchemeRef returns a local reference to a named security scheme component.

func (SecurityScheme) MarshalJSON

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

MarshalJSON renders the security scheme and its specification extensions.

type SecuritySchemeType

type SecuritySchemeType string

SecuritySchemeType identifies an OpenAPI security scheme kind.

const (
	// SecuritySchemeAPIKey authenticates with a named request value.
	SecuritySchemeAPIKey SecuritySchemeType = "apiKey"
	// SecuritySchemeHTTP authenticates with an HTTP authentication scheme.
	SecuritySchemeHTTP SecuritySchemeType = "http"
	// SecuritySchemeMutualTLS authenticates with mutual TLS.
	SecuritySchemeMutualTLS SecuritySchemeType = "mutualTLS"
	// SecuritySchemeOAuth2 authenticates through OAuth 2.0 flows.
	SecuritySchemeOAuth2 SecuritySchemeType = "oauth2"
	// SecuritySchemeOpenIDConnect authenticates through OpenID Connect discovery.
	SecuritySchemeOpenIDConnect SecuritySchemeType = "openIdConnect"
)

type Server

type Server struct {
	// URL is the server URL or URL template.
	URL string `json:"url"`
	// Description explains the server's purpose.
	Description string `json:"description,omitempty"`
	// Variables defines substitutions used by the URL template.
	Variables map[string]ServerVariable `json:"variables,omitempty"`
	// Extensions contains specification extensions for the server.
	Extensions Extensions `json:"-"`
}

Server describes one target server for the API.

func (Server) MarshalJSON

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

MarshalJSON renders the server and its specification extensions.

type ServerVariable

type ServerVariable struct {
	// Enum limits the variable to an allowed set of values.
	Enum []string `json:"enum,omitempty"`
	// Default is the value used when no substitution is supplied.
	Default string `json:"default"`
	// Description explains the variable's purpose.
	Description string `json:"description,omitempty"`
	// Extensions contains specification extensions for the variable.
	Extensions Extensions `json:"-"`
}

ServerVariable describes a substituted value in a server URL template.

func (ServerVariable) MarshalJSON

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

MarshalJSON renders the server variable and its specification extensions.

type SwaggerViewData added in v0.4.0

type SwaggerViewData struct {
	view.Page
	Version            string
	SpecPath           string
	UIPath             string
	Locale             string
	Favicon            string
	BackURL            string
	BackText           string
	BackTarget         string
	DisableThemeToggle bool
	LogoURL            string
	LogoAlt            string
	LogoHref           string
	LogoTarget         string
	// Translations holds Config.Translations, which Translate consults
	// before the package's own text.
	Translations map[string]string
}

SwaggerViewData is the data payload provided to the Kyse view.

func (SwaggerViewData) BackTextOrDefault added in v0.4.0

func (d SwaggerViewData) BackTextOrDefault() string

BackTextOrDefault returns the back link label localized according to Locale.

func (SwaggerViewData) BackURLOrDefault added in v0.4.0

func (d SwaggerViewData) BackURLOrDefault() string

BackURLOrDefault returns the URL to return to the site, defaulting to HomeURLOrDefault.

func (SwaggerViewData) BrandOrDefault added in v0.4.0

func (d SwaggerViewData) BrandOrDefault() string

BrandOrDefault returns the brand name, preferring LogoAlt, then AppName, then the page Title.

func (SwaggerViewData) FaviconOrDefault added in v0.4.0

func (d SwaggerViewData) FaviconOrDefault() string

FaviconOrDefault returns the favicon path, defaulting to /favicon.ico.

func (SwaggerViewData) HomeURLOrDefault added in v0.4.0

func (d SwaggerViewData) HomeURLOrDefault() string

HomeURLOrDefault returns the home URL, preferring LogoHref, then HomeURL, then /.

func (SwaggerViewData) LogoURLOrDefault added in v0.4.0

func (d SwaggerViewData) LogoURLOrDefault() string

LogoURLOrDefault returns the configured logo URL. It is empty when no logo is configured, because no image path is known to exist in every application; a template draws the logo only when the result is non-empty.

func (SwaggerViewData) Translate added in v0.4.4

func (d SwaggerViewData) Translate(key string) string

Translate returns the text drawn for key, one of the English strings the published views write, in the page's Locale: a Translations entry for key wins when it is not blank, then the package's Portuguese for pt and pt-BR, then key itself. It reads the Locale and Config.Translations the embedded page and the Swagger UI initializer read, so the whole page follows them.

type Tag

type Tag struct {
	// Name is the tag used by operations.
	Name string `json:"name"`
	// Description explains the tagged group of operations.
	Description string `json:"description,omitempty"`
	// ExternalDocs links to additional documentation for the tag.
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
	// Extensions contains specification extensions for the tag.
	Extensions Extensions `json:"-"`
}

Tag adds metadata to an operation tag.

func (Tag) MarshalJSON

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

MarshalJSON renders the tag and its specification extensions.

type Theme added in v0.4.0

type Theme struct {
	// Title overrides the HTML document title. When empty, Config.Title is used.
	Title string
	// DarkMode starts the UI in the dark palette.
	DarkMode bool
	// Locale specifies the UI language (e.g. "pt-BR", "en").
	Locale string
	// Translations supplies custom translation overrides.
	Translations map[string]string
	// ViewName specifies the Kyse view name rendered for the UI endpoint.
	ViewName string
	// PrimaryColor sets the accent color for buttons, badges, links, and highlights
	// (e.g. "#14b8a6", "#5eead4", or any valid CSS color).
	PrimaryColor string
	// BackgroundColor overrides the page background color (default "#0a0a0a" in dark mode).
	BackgroundColor string
	// CardColor overrides the card/container background color (default "#121214" in dark mode).
	CardColor string
	// TextColor overrides the primary text color (default "#f4f4f5" in dark mode).
	TextColor string
	// MutedColor overrides subtle/secondary text (default "#a1a1aa" in dark mode).
	MutedColor string
	// BorderColor overrides borders (default "#27272a" in dark mode).
	BorderColor string
	// the topbar draws no image, names the documentation by its title, and links
	// home to "/".
	Logo *ThemeLogo
	// BackURL configures the "Voltar para o site" link target in the topbar.
	// When empty, defaults to ThemeLogo.Href or "/".
	BackURL string
	// BackText overrides the back link text (defaults to "Voltar para o site" for pt/pt-BR and "Back to site" for other locales).
	BackText string
	// BackTarget is the anchor target for the back link (defaults to "_self").
	BackTarget string
	// DisableThemeToggle hides the light/dark theme switch in the topbar.
	DisableThemeToggle bool
	// Favicon is the URL to a custom favicon (e.g. "/favicon.ico" or "/favicon.png").
	// It follows the rules of ThemeLogo.URL: an absolute URL must use https, and
	// its origin is added to the page's img-src directive.
	Favicon string
	// CustomCSS is custom CSS appended to the theme stylesheet.
	CustomCSS string
	// CustomJS is custom JavaScript served and executed on the page.
	CustomJS string
	// HTMX configures HTMX-specific compatibility options.
	HTMX HTMXConfig
}

Theme controls visual styling, dark mode, custom colors, branding, and HTMX behavior.

type ThemeLogo struct {
	// URL is the image URL or data URI of the logo. A same-origin path or a
	// data URI needs nothing more; an absolute URL must use https, and its
	// origin is added to the page's img-src directive.
	URL string
	// Href is the link target when clicking the logo (defaults to "/").
	Href string
	// Alt is the alternative text for the logo (defaults to the API title).
	Alt string
	// Target is the anchor target, e.g. "_blank" or "_self" (defaults to "_self").
	Target string
}

ThemeLogo configures the brand logo in the Swagger UI topbar.

type Webhook added in v0.4.9

type Webhook struct {
	// Name is the key of the webhook in the document: usually the event name a
	// consumer subscribes to, such as "order.paid".
	Name string
	// Method is the HTTP method the provider sends with. Empty means POST.
	Method string
	// OperationID identifies the operation. It shares the document's
	// operationId namespace with every route operation.
	OperationID string
	// Summary is a short description of the event.
	Summary string
	// Description is the full description of the event and its delivery.
	Description string
	// Tags groups the webhook for readers and tooling.
	Tags []string
	// ExternalDocs links to additional documentation for the webhook.
	ExternalDocs *ExternalDocumentation
	// Parameters documents the headers, query or cookie values the provider
	// sends, such as a signature header. A webhook has no path parameters.
	Parameters []*Parameter
	// Body lists the representations of the request body the endpoint
	// receives. The provider always sends the body it declares, so a webhook
	// with a body has a required request body.
	Body []*Media
	// Responses are the answers the provider expects from the endpoint, keyed
	// by status code, by a status range such as "2XX", or by "default".
	Responses Responses
	// Security lists the requirements the provider satisfies when it sends.
	Security []SecurityRequirement
	// Deprecated marks an event that is kept for old subscriptions only.
	Deprecated bool
	// Extensions contains specification extensions for the operation.
	Extensions Extensions
}

Webhook is one request the API sends to an endpoint its consumer registered: an event the provider initiates, written into the document's OpenAPI 3.1 webhooks section rather than its paths.

A webhook is not a route of the application's router, so the route table cannot describe it. The values come from the application's own catalogue of the events it sends -- the list a subscription is validated against -- and are registered on the same registry as the routes, so the document has one source for its paths and one for its webhooks and keeps no second, hand-written specification:

webhooks := make([]swagger.Webhook, 0, len(events.Names()))
for _, name := range events.Names() {
	webhooks = append(webhooks, swagger.Webhook{
		Name:      name,
		Summary:   "Sent when " + name + " happens.",
		Body:      []*swagger.Media{swagger.JSONRef("Event")},
		Responses: swagger.Responses{"2XX": {Description: "Received."}},
	})
}
err := docs.Webhooks(webhooks...)

Directories

Path Synopsis
examples
basic
Package basic demonstrates explicit Arandu Swagger wiring and route-local documentation with native Hesape schemas.
Package basic demonstrates explicit Arandu Swagger wiring and route-local documentation with native Hesape schemas.
static command
Command static-openapi generates OpenAPI JSON without starting an HTTP server.
Command static-openapi generates OpenAPI JSON without starting an HTTP server.
internal
ui
Package ui provides the self-hosted Swagger UI distribution assets.
Package ui provides the self-hosted Swagger UI distribution assets.
tests

Jump to

Keyboard shortcuts

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