Documentation
¶
Overview ¶
Package stdocs builds an OpenAPI 3.0, 3.1, or 3.2 specification from routes registered on a standard library net/http.ServeMux and serves the spec (and an optional docs UI) over HTTP.
The pattern syntax it documents ("GET /users/{id}") is the method+path routing introduced in Go 1.22; the module itself requires Go 1.26.4 or later.
Two ways to use it ¶
New returns a Mux — an *http.ServeMux wrapper that records route metadata as you register handlers and generates the OpenAPI document from it. This is the recommended way to use stdocs.
DocsHandler serves a docs UI for a hand-written OpenAPI document supplied via WithSpec, without introspecting any mux.
Example ¶
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
func getUser(w http.ResponseWriter, r *http.Request) { /* ... */ }
func main() {
mux := stdocs.New(
stdocs.WithTitle("My API"),
stdocs.WithVersion(stdocs.OpenAPI31),
stdocs.WithBearerAuth("bearerAuth", "JWT"),
)
mux.HandleFunc("GET /users/{id}", getUser,
stdocs.Summary("Get user by id"),
stdocs.WithResponse(200, User{}),
stdocs.WithSecurity("bearerAuth"),
)
mux.Mount() // docs UI at /docs/, spec at /docs/openapi.json
log.Fatal(http.ListenAndServe(":8080", mux))
}
Serve the mux itself (it is the http.Handler for your routes). To mount it under a sub-path, wrap it with net/http.StripPrefix — note the generated spec paths will not include the stripped prefix.
Options and route opts ¶
Mux-level configuration uses Option values passed to New or DocsHandler (all named With*, e.g. WithTitle, WithVersion, WithDocsPrefix, WithDisabled). Per-route documentation uses RouteOpt values passed to Mux.HandleFunc / Mux.Handle: bare-named opts set simple operation metadata (Summary, Description, Tags, Deprecated, OperationID, Optional), while opts that attach bodies, responses, parameters, or security are named With* (WithBody, WithResponse, WithParam, WithSecurity, ...).
OpenAPI versions ¶
stdocs emits the latest patch of each supported minor: OpenAPI30 (3.0.4, the default), OpenAPI31 (3.1.2), and OpenAPI32 (3.2.0). Select one with WithVersion. For 3.2, WithSelfURL sets the document's canonical URI ($self).
Index ¶
- Constants
- func DocsHandler(opts ...Option) http.Handler
- type Config
- type Contact
- type Info
- type License
- type Mux
- func (m *Mux) Config() *Config
- func (m *Mux) Docs(enabled ...bool) http.Handler
- func (m *Mux) Handle(p string, h http.Handler, opts ...RouteOpt)
- func (m *Mux) HandleFunc(p string, h func(http.ResponseWriter, *http.Request), opts ...RouteOpt)
- func (m *Mux) JSON() ([]byte, error)
- func (m *Mux) Mount()
- func (m *Mux) Refresh()
- func (m *Mux) YAML() ([]byte, error)
- type OAuthFlow
- type OAuthFlows
- type Operation
- type Option
- func WithAPIKeyAuth(name, in, paramName string) Option
- func WithAPIVersion(v string) Option
- func WithBasicAuth(name string) Option
- func WithBearerAuth(name, bearerFormat string) Option
- func WithContact(name, email, url string) Option
- func WithDefaultSummary(template string) Option
- func WithDescription(s string) Option
- func WithDisabled(disabled bool) Option
- func WithDocsPrefix(prefix string) Option
- func WithGlobalSecurity(name string, scopes ...string) Option
- func WithLicense(name, url string) Option
- func WithOAuth2Auth(name string, flows OAuthFlows) Option
- func WithOpenAPI(fn func(doc map[string]any)) Option
- func WithSecurityScheme(name string, scheme SecurityScheme) Option
- func WithSelfURL(selfURL string) Option
- func WithServer(url, description string) Option
- func WithSpec(specJSON []byte) Option
- func WithTag(name, description string) Option
- func WithTitle(title string) Option
- func WithVersion(v SpecVersion) Option
- func WithWebhooks(hooks map[string]Webhook) Option
- type Param
- type PathItem
- type RequestBody
- type Response
- type RouteOpt
- func CookieParam(name, typ, desc string) RouteOpt
- func Deprecated() RouteOpt
- func Description(s string) RouteOpt
- func HeaderParam(name, typ, desc string) RouteOpt
- func OperationID(id string) RouteOpt
- func Optional() RouteOpt
- func QueryParam(name, typ, desc string) RouteOpt
- func Summary(s string) RouteOpt
- func Tags(names ...string) RouteOpt
- func WithBody(body any) RouteOpt
- func WithBodyContentType(ct string) RouteOpt
- func WithExample(value any) RouteOpt
- func WithNoSecurity() RouteOpt
- func WithParam(name, in, typ, description string) RouteOpt
- func WithResponse(status int, body any) RouteOpt
- func WithResponseDescription(status int, description string) RouteOpt
- func WithResponseExample(status int, value any) RouteOpt
- func WithResponseHeader(status int, name, typ, description string) RouteOpt
- func WithSecurity(name string, scopes ...string) RouteOpt
- type SecurityRequirement
- type SecurityScheme
- type SecuritySchemeType
- type Server
- type SpecInput
- type SpecVersion
- type TagDecl
- type Webhook
Examples ¶
Constants ¶
const ( SecurityHTTP = spec.SecurityHTTP SecurityAPIKey = spec.SecurityAPIKey SecurityOAuth2 = spec.SecurityOAuth2 SecurityOpenIDConnect = spec.SecurityOpenIDConnect SecurityAPIKeyInHeader = spec.SecurityAPIKeyInHeader SecurityAPIKeyInQuery = spec.SecurityAPIKeyInQuery SecurityAPIKeyInCookie = spec.SecurityAPIKeyInCookie )
const ( // OpenAPI30 is the latest 3.0.x patch (3.0.4), the default. OpenAPI30 = version.OpenAPI30 // OpenAPI31 is the latest 3.1.x patch (3.1.2). OpenAPI31 = version.OpenAPI31 // OpenAPI32 is the latest 3.2.x patch (3.2.0). OpenAPI32 = version.OpenAPI32 )
The version constants accepted by WithVersion: the latest patch of each supported OpenAPI minor.
Variables ¶
This section is empty.
Functions ¶
func DocsHandler ¶
DocsHandler returns an http.Handler that serves the docs UI and a static OpenAPI spec. This is the Tier-1 entry point: it does not introspect any mux. Provide the document with WithSpec; without it, a minimal valid placeholder built from WithTitle / WithAPIVersion / WithVersion is served, so every bundled UI still renders.
The handler serves:
GET <prefix>/ -> the HTML docs UI GET <prefix>/openapi.json -> the spec as JSON GET <prefix>/openapi.yaml -> the spec as YAML
To customise the docs UI, pass a UI option from one of the github.com/FumingPower3925/stdocs/ui/* sub-packages:
mux := http.NewServeMux()
mux.Handle("GET /docs/", stdocs.DocsHandler(
stdocs.WithTitle("My API"),
scalar.WithUI(),
))
mux.HandleFunc("GET /users", listUsers)
If you want a spec generated from registered routes instead, use Tier 2: build the application on a *stdocs.Mux (see New).
If WithDisabled(true) is passed, the returned handler responds with 404 on every request, equivalent to Mux.Docs(false).
Example ¶
Serving a docs UI for a hand-written spec (Tier 1) — no route introspection involved.
package main
import (
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
spec := []byte(`{"openapi":"3.0.4","info":{"title":"Hand-written","version":"1.0.0"},"paths":{}}`)
mux := http.NewServeMux()
mux.Handle("GET /docs/", stdocs.DocsHandler(
stdocs.WithTitle("Hand-written"),
stdocs.WithSpec(spec),
))
fmt.Println("docs mounted")
}
Output: docs mounted
Types ¶
type Config ¶
type Config struct {
// Info carries the OpenAPI "info" object.
Info Info
// Servers is the list of OpenAPI "servers".
Servers []Server
// Tags are the declared top-level tags. Tags attached to operations
// that aren't in this list are still emitted on the operation; the
// declarations are just for richer descriptions.
Tags []TagDecl
// DocsPrefix is the URL prefix under which the docs UI and spec are
// served. Defaults to "/docs".
DocsPrefix string
// SelfURL is the OpenAPI 3.2 "$self" field — the canonical URI
// of the document. When non-empty, the 3.2 emitter includes it
// in the spec root. Ignored for 3.0 and 3.1 (the field does
// not exist in those versions).
SelfURL string
// Version is the OpenAPI version to emit. Defaults to OpenAPI30.
Version SpecVersion
// DefaultSummary is a fallback summary used for routes that have
// neither a per-route Summary nor a function-name-based inference.
DefaultSummary string
// UIDoc is the HTML template for the docs UI page. The default is
// the small dependency-free page in stdocs.defaultUIDoc. UI
// sub-packages override this field via a stdocs.Option to swap in
// their own page. The template may contain {{.Title}} and
// {{.SpecURL}} placeholders; the page is rendered once, when the
// docs handler is constructed.
UIDoc string
// Hooks is the list of post-build callbacks registered via
// WithOpenAPI. Each is called once per spec build, with the
// emitted spec as a map[string]any, and may mutate it in place.
Hooks []func(doc map[string]any)
// Security is the list of registered security schemes. The user
// adds entries via WithSecurityScheme / WithBearerAuth / etc.;
// each is rendered into components.securitySchemes at build time.
Security []spec.NamedSecurityScheme
// GlobalSecurity is the default security requirement applied to
// every operation. Operations may override with WithSecurity or
// opt out with WithNoSecurity.
GlobalSecurity []SecurityRequirement
// Webhooks are emitted for 3.1 and 3.2 specs and ignored for 3.0
// (the field does not exist there). The map is keyed by webhook
// name.
Webhooks map[string]Webhook
// Disabled turns off the docs handler. When true, Mux.Docs and
// DocsHandler return a 404 handler instead of serving the UI and
// the spec. Mux.Mount respects this and registers nothing.
Disabled bool
// StaticSpec is a hand-written OpenAPI document (JSON bytes) set
// via WithSpec. It is served verbatim by DocsHandler (Tier 1) and
// ignored by *Mux (Tier 2), which generates its own document.
StaticSpec []byte
}
Config holds the resolved configuration for an stdocs Mux. It is built by applying a list of Options to a fresh Config and is shared with the registry and the spec emitter.
Config is exported (rather than unexported like in many libraries) so that UI sub-packages (e.g. stdocs/ui/scalar) can mutate it via a stdocs.Option. UI sub-packages should not construct or copy a Config; they should only read or write the UIDoc field.
type Contact ¶
Contact is the OpenAPI "info.contact" object. Fields: Name, URL, Email. Set via WithContact; empty fields are omitted from the document.
type Info ¶
Info is the OpenAPI "info" object. Fields: Title, Version, Description, TermsOfService, Contact (*Contact), License (*License). Title and Version are set via WithTitle and WithAPIVersion.
type License ¶
License is the OpenAPI "info.license" object. Fields: Name, URL. Set via WithLicense; empty fields are omitted.
type Mux ¶
Mux is an *http.ServeMux that also records route metadata for OpenAPI generation. Use stdocs.New to construct one. Mux embeds *http.ServeMux, so all its methods are available transparently.
func New ¶
New returns a *stdocs.Mux ready to register routes on.
Example ¶
The simplest possible setup: wrap the mux, register routes, mount the docs, serve. The generated document is available programmatically through JSON() too.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
mux := stdocs.New(stdocs.WithTitle("My API"))
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {})
mux.Mount() // docs UI at /docs/, spec at /docs/openapi.json
b, _ := mux.JSON()
var doc struct {
OpenAPI string `json:"openapi"`
Info struct {
Title string `json:"title"`
} `json:"info"`
}
_ = json.Unmarshal(b, &doc)
fmt.Println(doc.OpenAPI, doc.Info.Title)
}
Output: 3.0.4 My API
func (*Mux) Config ¶
Config returns the resolved configuration for the mux. It is useful for UI sub-packages that need to read or override Config fields.
func (*Mux) Docs ¶
Docs returns an http.Handler that serves the docs UI and the OpenAPI spec for this mux. The returned handler is a sub-mux that internally serves:
GET <prefix>/ -> the HTML docs UI GET <prefix>/openapi.json -> the spec as JSON GET <prefix>/openapi.yaml -> the spec as YAML
In most setups, call Mount instead, which registers this handler at the configured docs prefix (default "/docs", changeable via WithDocsPrefix). When mounting manually, the registration pattern must match the configured prefix:
mux.ServeMux.Handle("GET /docs/", mux.Docs())
(Plain mux.Handle works too — routes under the docs prefix are excluded from the generated spec.)
The optional bool argument enables per-call toggling: pass false to get a handler that responds 404 to everything, pass true to force the docs on, or omit it to follow the WithDisabled config. An explicit per-call value wins over WithDisabled in both directions. Only the first value is consulted; passing more than one bool panics.
mux.ServeMux.Handle("GET /docs/", mux.Docs(os.Getenv("ENV") != "prod"))
The decision is taken when Docs is called. For a per-request switch, wrap the returned handler in your own middleware.
Example ¶
Turning the docs off per environment without touching routes.
package main
import (
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
prod := true
mux := stdocs.New(stdocs.WithTitle("My API"))
mux.HandleFunc("GET /users", func(w http.ResponseWriter, r *http.Request) {})
// An explicit per-call value wins over WithDisabled in both
// directions; mux.Docs(false) serves 404 for every docs request.
mux.ServeMux.Handle("GET /docs/", mux.Docs(!prod))
fmt.Println("docs enabled:", !prod)
}
Output: docs enabled: false
func (*Mux) Handle ¶
Handle registers h for the given pattern. The handler's underlying function name cannot be recovered from an http.Handler, so routes registered via Handle do not benefit from function-name-based summary inference (they get a blank summary unless Summary is provided).
func (*Mux) HandleFunc ¶
HandleFunc registers h for the given pattern. opts are RouteOpts that document the route.
The pattern must be a Go 1.22+ ServeMux pattern (e.g. "GET /users/{id}"). If parsing fails, HandleFunc panics. This matches the stdlib's behavior of panicking on invalid patterns.
func (*Mux) JSON ¶
JSON returns the OpenAPI spec as JSON bytes. The version depends on the mux's configured Version. First call is cached.
func (*Mux) Mount ¶
func (m *Mux) Mount()
Mount registers the docs handler on the mux itself, at the configured DocsPrefix (default "/docs"). It registers exact patterns for the docs page and the two spec endpoints — plus a subtree fallback — so a user route like "GET /docs/{file}" can never shadow the spec endpoints (exact literals win over wildcards in ServeMux).
If the mux has been disabled via WithDisabled, Mount is a no-op and registers nothing. Calling Mount more than once is a no-op after the first successful registration. Call it after registering all routes.
type OAuthFlow ¶
OAuthFlow describes one OAuth 2.0 flow. Fields: AuthorizationURL, TokenURL, RefreshURL, DeviceAuthorizationURL (3.2 device flow only), and Scopes (scope name -> description; always emitted, required by the spec).
type OAuthFlows ¶
type OAuthFlows = spec.OAuthFlows
OAuthFlows groups the OAuth 2.0 flows of a scheme: Implicit, Password, ClientCredentials, AuthorizationCode, and (OpenAPI 3.2 only) DeviceAuthorization — each an optional *OAuthFlow.
type Operation ¶
Operation is the per-route OpenAPI operation under construction. It is the value RouteOpts mutate; most users never touch it directly.
type Option ¶
type Option func(*Config)
Option is a function that mutates a config. Options are applied by New and DocsHandler at construction time.
func WithAPIKeyAuth ¶
WithAPIKeyAuth is a convenience for API key authentication. in is one of stdocs.SecurityAPIKeyInHeader, stdocs.SecurityAPIKeyInQuery, stdocs.SecurityAPIKeyInCookie.
func WithAPIVersion ¶
WithAPIVersion sets the API version string in the OpenAPI "info" block (e.g. "1.0.0"). This is independent of WithVersion which sets the OpenAPI specification version (3.0.4 vs 3.1.2 vs 3.2.0).
func WithBasicAuth ¶
WithBasicAuth is a convenience for HTTP basic authentication.
func WithBearerAuth ¶
WithBearerAuth is a convenience for HTTP bearer authentication.
Example ¶
Registering a security scheme and requiring it on a route.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
mux := stdocs.New(
stdocs.WithTitle("My API"),
stdocs.WithBearerAuth("bearerAuth", "JWT"),
stdocs.WithGlobalSecurity("bearerAuth"),
)
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {},
stdocs.WithNoSecurity(), // public route opts out of the global scheme
)
b, _ := mux.JSON()
var doc struct {
Paths map[string]map[string]struct {
Security []map[string][]string `json:"security"`
} `json:"paths"`
}
_ = json.Unmarshal(b, &doc)
fmt.Println(len(doc.Paths["/health"]["get"].Security))
}
Output: 0
func WithContact ¶
WithContact sets the contact info.
func WithDefaultSummary ¶
WithDefaultSummary sets a default summary template used for routes that do not provide one and whose function name does not yield a useful inference. Use {resource} as a placeholder for the first path segment (the inferred tag).
func WithDescription ¶
WithDescription sets the API description.
func WithDisabled ¶
WithDisabled turns off the docs UI and the spec endpoints. Useful for environment-based toggling (e.g. don't expose docs in production, or behind a feature flag):
mux := stdocs.New(
stdocs.WithDisabled(os.Getenv("ENV") == "prod"),
)
When the mux is disabled, Mux.Docs returns a 404 handler and Mux.Mount registers nothing. JSON and YAML still produce the spec bytes — disabling the docs UI does not stop spec generation.
For per-call toggling (e.g. a config that may change at runtime), pass the bool directly to Mux.Docs(enabled) instead.
func WithDocsPrefix ¶
WithDocsPrefix overrides the URL prefix for the docs UI. The default is "/docs". The value is normalized: a leading slash is added if missing, and a trailing slash is removed so the prefix is comparable to strings.TrimPrefix results. An empty prefix is replaced with the default "/docs"; to turn the docs UI off, use WithDisabled or pass false to Mux.Docs.
The root prefix "/" is rejected with a panic: it would claim the whole URL space and produce an invalid ServeMux pattern in Mount.
func WithGlobalSecurity ¶
WithGlobalSecurity sets the default security requirement applied to every operation that does not specify its own. Operations can opt out with stdocs.WithNoSecurity or override with stdocs.WithSecurity.
stdocs.WithGlobalSecurity("bearerAuth")
stdocs.WithGlobalSecurity("oauth2Auth", "read:users")
func WithOAuth2Auth ¶
func WithOAuth2Auth(name string, flows OAuthFlows) Option
WithOAuth2Auth is a convenience for OAuth 2.0 with one or more flows.
func WithOpenAPI ¶
WithOpenAPI registers a callback that runs after the spec is built and before it is cached. The callback receives the spec as a map[string]any and may mutate it in place. This is the escape hatch for features stdocs does not expose directly: security schemes, webhooks, custom x-extensions, vendor extensions, etc.
The callback is invoked once per build (i.e. once before the cache is populated; subsequent reads use the cache). Call Refresh to force the callback to run again.
Example:
stdocs.WithOpenAPI(func(doc map[string]any) {
doc["security"] = []map[string]any{{
"bearerAuth": []string{},
}}
doc["components"].(map[string]any)["securitySchemes"] = map[string]any{
"bearerAuth": map[string]any{
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
},
}
})
func WithSecurityScheme ¶
func WithSecurityScheme(name string, scheme SecurityScheme) Option
WithSecurityScheme registers a security scheme under the given name. The name is the key in the components.securitySchemes map and is the value you pass to WithSecurity on a route. If name is empty, a sensible default is chosen (e.g. "bearerAuth" for HTTP bearer).
Use the chosen name with WithSecurity to require this scheme on a route.
func WithSelfURL ¶
WithSelfURL sets the OpenAPI 3.2 "$self" field. This is the canonical URI of the document. It is emitted only in 3.2 specs; setting it on a 3.0 or 3.1 mux has no effect because those versions do not have the field.
The value must be a valid RFC 3986 URI reference without a fragment (both constraints come from the OpenAPI 3.2 specification and its published JSON Schema). WithSelfURL panics on invalid input, consistent with WithVersion's fail-fast behavior at New()/DocsHandler() time.
func WithSpec ¶
WithSpec sets a static OpenAPI document (JSON bytes) for DocsHandler to serve at <prefix>/openapi.json (and, converted, at <prefix>/openapi.yaml). This is the Tier-1 path for exposing a hand-written spec through the docs UI:
specJSON, _ := os.ReadFile("openapi.json")
mux.Handle("GET /docs/", stdocs.DocsHandler(
stdocs.WithTitle("My API"),
stdocs.WithSpec(specJSON),
))
WithSpec has no effect on *stdocs.Mux (Tier 2), which always generates its spec from the registered routes.
func WithTag ¶
WithTag declares a top-level tag and its description. Tags attached to operations that match a declared tag are also valid; undeclared tags are still emitted.
func WithVersion ¶
func WithVersion(v SpecVersion) Option
WithVersion sets the OpenAPI spec version. Accepts OpenAPI30 (3.0.4), OpenAPI31 (3.1.2), or OpenAPI32 (3.2.0). A string literal like "3.0.4" is also accepted because SpecVersion is a defined string type with the same underlying values.
WithVersion panics on an unknown version string. Options run at New()/DocsHandler() time, the same fail-fast window where bad patterns already panic; silently coercing to a default would mask user errors.
Example ¶
Selecting the OpenAPI version. stdocs ships the latest patch of each supported minor: 3.0.4 (default), 3.1.2, and 3.2.0.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
mux := stdocs.New(
stdocs.WithTitle("My API"),
stdocs.WithVersion(stdocs.OpenAPI32),
stdocs.WithSelfURL("https://api.example.com/openapi.json"),
)
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {})
b, _ := mux.JSON()
var doc struct {
OpenAPI string `json:"openapi"`
Self string `json:"$self"`
}
_ = json.Unmarshal(b, &doc)
fmt.Println(doc.OpenAPI, doc.Self)
}
Output: 3.2.0 https://api.example.com/openapi.json
func WithWebhooks ¶
WithWebhooks registers one or more webhooks under their given names. Webhooks require OpenAPI 3.1 or 3.2; on 3.0 they are silently ignored (the field does not exist in that version).
Webhook payloads are described the same way route bodies are: set RequestBody.BodyValue (or Response.BodyValue) to a zero value of the Go type and its JSON Schema is reflected when the document is built.
Example:
type UserPayload struct {
ID string `json:"id"`
}
stdocs.WithWebhooks(map[string]stdocs.Webhook{
"newUser": {
Method: "POST",
Summary: "New user created",
RequestBody: &stdocs.RequestBody{Required: true, BodyValue: UserPayload{}},
Responses: map[string]*stdocs.Response{
"200": {Description: "OK"},
},
},
})
type Param ¶
Param describes one OpenAPI parameter. Fields: Name, In ("path", "query", "header", "cookie"), Required, Description, Schema. Usually created via WithParam / QueryParam / HeaderParam / CookieParam.
type PathItem ¶
PathItem groups the operations of one path. Produced internally by the registry; exposed for advanced use only.
type RequestBody ¶
type RequestBody = spec.RequestBody
RequestBody describes an operation's request body. Fields: Description, Required, ContentType (defaults to "application/json"), Example, and BodyValue — a zero value of the Go body type, reflected at document-build time. Usually created via WithBody; constructed directly only for webhooks.
type Response ¶
Response describes one entry of an operation's "responses" map. Fields: Status, Description, Headers, Example, and BodyValue — a zero value of the Go response type, reflected into a JSON Schema at document-build time. Usually created via WithResponse and decorated with WithResponseDescription / WithResponseHeader / WithResponseExample; constructed directly only for webhooks.
type RouteOpt ¶
type RouteOpt func(*route)
RouteOpt is a function that mutates a route's metadata. RouteOpt is passed as variadic to *stdocs.Mux.HandleFunc and *stdocs.Mux.Handle.
func CookieParam ¶
CookieParam is shorthand for WithParam(name, "cookie", typ, desc).
func Description ¶
Description sets the route's longer Markdown description.
func HeaderParam ¶
HeaderParam is shorthand for WithParam(name, "header", typ, desc).
func OperationID ¶
OperationID sets the operationId. If not set, stdocs auto-derives one from the method and path.
func Optional ¶
func Optional() RouteOpt
Optional marks the route's request body as not required. Only meaningful when called after WithBody.
func QueryParam ¶
QueryParam is shorthand for WithParam(name, "query", typ, desc).
func Summary ¶
Summary sets the route's summary (the short single-line description shown next to the operation in UIs).
func WithBody ¶
WithBody sets the route's request body. body is a zero value of the type to reflect; its type is used to build the JSON Schema when the spec document is assembled. The default content type is application/json (override with WithBodyContentType).
Mark the body as not required with Optional().
func WithBodyContentType ¶
WithBodyContentType sets the content type for the request body, creating the request-body entry if it does not exist yet. The default is "application/json". The order relative to WithBody does not matter.
stdocs.WithBody(MyRequest{}),
stdocs.WithBodyContentType("application/xml"),
func WithExample ¶
WithExample adds an example value to the request body if one has been declared (via WithBody), otherwise to the most recently declared response (via WithResponse). If neither has been declared, WithExample is a no-op. To target a specific response regardless of declaration order, use WithResponseExample.
The value is encoded as JSON and stored under the OpenAPI "example" field of the media type object (content.<type>.example).
Example:
mux.HandleFunc("POST /users", createUser,
stdocs.WithBody(CreateUserRequest{}),
stdocs.WithResponse(201, User{}),
stdocs.WithExample(CreateUserRequest{Title: "Buy milk"}),
)
Subsequent WithExample calls overwrite the previous example.
func WithNoSecurity ¶
func WithNoSecurity() RouteOpt
WithNoSecurity opts the operation out of any security requirement. This emits an empty `security: []` array at the operation level, which the OpenAPI spec defines as overriding a globally-applied scheme. Without this (i.e. leaving Security empty), the operation inherits the global security requirement.
func WithParam ¶
WithParam adds a parameter to the route. in is one of "path", "query", "header", "cookie". typ is the JSON Schema type name ("string", "integer", "number", "boolean", "array"). For arrays, the items are also string-typed.
Multiple WithParam calls accumulate.
func WithResponse ¶
WithResponse adds a response entry. body is a zero value whose type is reflected into a JSON Schema when the spec document is assembled; pass nil if there is no body (e.g. 204 No Content). Multiple WithResponse calls accumulate. Calling WithResponse twice for the same status replaces the body but keeps any description, headers, or example attached via the other response opts.
Example ¶
Documenting request and response bodies through reflection.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/FumingPower3925/stdocs"
)
func main() {
type User struct {
ID string `json:"id" doc:"Unique ID"`
Name string `json:"name"`
}
type CreateUserRequest struct {
Name string `json:"name"`
}
mux := stdocs.New(stdocs.WithTitle("My API"))
mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {},
stdocs.Summary("Create a user"),
stdocs.WithBody(CreateUserRequest{}),
stdocs.WithResponse(201, User{}),
stdocs.WithResponseDescription(201, "The newly created user"),
)
b, _ := mux.JSON()
var doc struct {
Components struct {
Schemas map[string]json.RawMessage `json:"schemas"`
} `json:"components"`
}
_ = json.Unmarshal(b, &doc)
for name := range doc.Components.Schemas {
if name == "User" {
fmt.Println("components.schemas has User")
}
}
}
Output: components.schemas has User
func WithResponseDescription ¶
WithResponseDescription sets a custom description for a response status, creating the response entry if it does not exist yet. The order relative to WithResponse does not matter.
stdocs.WithResponse(200, User{}),
stdocs.WithResponseDescription(200, "The user, or 404 if not found"),
func WithResponseExample ¶
WithResponseExample attaches an example to a specific response status, creating the response entry if it does not exist yet. The order relative to WithResponse does not matter.
stdocs.WithResponse(200, User{}),
stdocs.WithResponseExample(200, User{ID: "u-1", Name: "Alice"}),
func WithResponseHeader ¶
WithResponseHeader adds a header entry to a response status, creating the response entry if it does not exist yet. Useful for documenting rate-limit, pagination, or other custom headers. The order relative to WithResponse does not matter.
stdocs.WithResponse(200, User{}),
stdocs.WithResponseHeader(200, "X-RateLimit-Remaining", "integer", "Remaining quota"),
func WithSecurity ¶
WithSecurity requires the named security scheme on this operation. scopes are only meaningful for OAuth2 schemes; pass no scopes for non-OAuth schemes.
Use WithNoSecurity to opt out of a globally-applied scheme for one route.
Example:
mux.HandleFunc("GET /me", getUser,
stdocs.WithSecurity("bearerAuth"),
)
mux.HandleFunc("POST /posts", createPost,
stdocs.WithSecurity("oauth2Auth", "write:posts", "read:posts"),
)
type SecurityRequirement ¶
type SecurityRequirement = spec.SecurityRequirement
SecurityRequirement is one entry of a "security" array: scheme name -> required scopes (empty for non-OAuth schemes).
type SecurityScheme ¶
type SecurityScheme = spec.SecurityScheme
SecurityScheme describes one components.securitySchemes entry. Set Type plus the type-specific fields: Scheme/BearerFormat for http, In/Name for apiKey, Flows for oauth2, and OpenIDConnectURL for openIdConnect. Description is optional.
type SecuritySchemeType ¶
type SecuritySchemeType = spec.SecuritySchemeType
SecuritySchemeType is the "type" of a security scheme: SecurityHTTP, SecurityAPIKey, SecurityOAuth2, or SecurityOpenIDConnect.
type Server ¶
Server is one OpenAPI "servers" entry. Fields: URL, Description. Added via WithServer (the default relative "/" entry stays first).
type SpecInput ¶
SpecInput is the input consumed by the internal emitters. Exposed for advanced use only.
type SpecVersion ¶
type SpecVersion = version.SpecVersion
SpecVersion is the OpenAPI spec version ("3.0.4", "3.1.2", or "3.2.0"). Use the OpenAPI30 / OpenAPI31 / OpenAPI32 constants with WithVersion.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
demo
command
Package main is a demo of stdocs using a fictional Task Tracker API.
|
Package main is a demo of stdocs using a fictional Task Tracker API. |
|
internal
|
|
|
pattern
Package pattern parses Go 1.22+ net/http.ServeMux pattern strings.
|
Package pattern parses Go 1.22+ net/http.ServeMux pattern strings. |
|
schema
Package schema reflects Go values into a version-agnostic JSON Schema representation consumed by the OpenAPI emitters in internal/spec.
|
Package schema reflects Go values into a version-agnostic JSON Schema representation consumed by the OpenAPI emitters in internal/spec. |
|
spec
Package spec builds OpenAPI 3.0, 3.1, and 3.2 documents from internal *spec.SpecInput values.
|
Package spec builds OpenAPI 3.0, 3.1, and 3.2 documents from internal *spec.SpecInput values. |
|
spec/yaml
Package yaml converts JSON documents (the form produced by the OpenAPI emitters) to YAML.
|
Package yaml converts JSON documents (the form produced by the OpenAPI emitters) to YAML. |
|
version
Package version defines the OpenAPI spec-version identifiers used by the emitters.
|
Package version defines the OpenAPI spec-version identifiers used by the emitters. |
|
ui
|
|
|
redoc
Package redoc provides a Redoc UI for stdocs.
|
Package redoc provides a Redoc UI for stdocs. |
|
redocemb
Package redocemb provides an embedded (air-gapped) Redoc UI for stdocs.
|
Package redocemb provides an embedded (air-gapped) Redoc UI for stdocs. |
|
scalar
Package scalar provides a Scalar UI for stdocs.
|
Package scalar provides a Scalar UI for stdocs. |
|
scalaremb
Package scalaremb provides an embedded (air-gapped) Scalar UI for stdocs.
|
Package scalaremb provides an embedded (air-gapped) Scalar UI for stdocs. |
|
stoplight
Package stoplight provides a Stoplight Elements UI for stdocs.
|
Package stoplight provides a Stoplight Elements UI for stdocs. |
|
stoplightemb
Package stoplightemb provides an embedded (air-gapped) Stoplight Elements UI for stdocs.
|
Package stoplightemb provides an embedded (air-gapped) Stoplight Elements UI for stdocs. |
|
swaggerui
Package swaggerui provides a Swagger UI for stdocs.
|
Package swaggerui provides a Swagger UI for stdocs. |
|
swaggeruiemb
Package swaggeruiemb provides an embedded (air-gapped) Swagger UI for stdocs.
|
Package swaggeruiemb provides an embedded (air-gapped) Swagger UI for stdocs. |