Appearance
API docs automation
teamusers generates its OpenAPI document from route walking plus co-located operation metadata, and renders the result into the API reference pages you are reading. Both halves are published for reuse by other Go services in the fleet:
| Artifact | Name | Purpose |
|---|---|---|
| Go module | github.com/crazy4chicken/nsc-teamusers/apidocs/go | Pair chi routes with operation metadata, emit deterministic OpenAPI 3.1 |
| npm package | teamusers-apidocs-vitepress | Turn the emitted spec into VitePress reference pages |
The pipeline is: doc.go metadata → genspec command → openapi.yaml → VitePress dynamic pages. The generator fails when a walked route has no metadata or metadata matches no route, so the reference can never silently drift from the router.
The docs site at a glance
The documentation is a VitePress site rooted at docs/, configured by docs/.vitepress/config.mts (top navigation, sidebar, theme). Its pages fall into two classes:
| Class | Location | Authoring |
|---|---|---|
| Guides | docs/guide/*.md | Hand-written Markdown; every page needs a hand-written sidebar entry in config.mts |
| API reference | docs/api/reference/ | Generated. One page per OpenAPI tag, produced by the dynamic route [tag].paths.ts + [tag].md from docs/public/openapi.yaml. Never hand-edit |
docs/public/openapi.yaml is itself generated by genspec and git-ignored. The site is built with plain VitePress commands, wrapped in npm scripts whose pre* hooks regenerate the spec first:
sh
pnpm docs:dev # local preview with hot reload
pnpm docs:build # static build into docs/.vitepress/distA consumer service replicates exactly this shape: hand-written guides for prose, generated reference pages for endpoints, one config.mts wiring both into the navigation. The sections below build it up — Go side first, then the VitePress side.
Go side
Install the module (tags live in the teamusers repository as apidocs/go/vX.Y.Z):
sh
go get github.com/crazy4chicken/nsc-teamusers/apidocs/go@v0.1.01. Declare operation metadata
Next to your handlers, declare one apidocs.Operation per route. Request and Response are zero values reflected into schemas; the examples are rendered verbatim into the page.
go
package httpapi
import apidocs "github.com/crazy4chicken/nsc-teamusers/apidocs/go"
var DocOperations = []apidocs.Operation{
{
Method: "GET",
Path: "/widgets/{id}",
Tag: "Widgets",
Summary: "Get a widget",
Description: "Use to retrieve one widget by ULID.",
Security: "admin", // any non-empty value marks the op as bearer-protected
Response: Widget{},
ResponseExample: map[string]any{
"id": "01J8Z3WIDGET00000000001", "name": "sprocket",
},
Errors: []apidocs.ErrorDoc{
{Status: 401, Code: "unauthorized", Title: "Unauthorized"},
{Status: 404, Code: "not_found", Title: "Not Found"},
},
},
}2. Generate the spec
Add a small command that walks your router and emits the document. The router must be constructible without a database — chi.Walk only inspects route patterns. If your constructors need dependencies, give them stubs at generation time (teamusers does this in internal/apidocsgen; most services can just call their plain constructors).
go
// cmd/genspec/main.go
package main
import (
"os"
apidocs "github.com/crazy4chicken/nsc-teamusers/apidocs/go"
"example.com/myservice/internal/httpapi"
)
func main() {
router := httpapi.NewRouter() // any constructible root router
operations, err := apidocs.Collect(router, httpapi.DocOperations, nil)
if err != nil {
panic(err) // route/metadata mismatch: fix doc.go or the route
}
out, err := os.Create("docs/public/openapi.yaml")
if err != nil {
panic(err)
}
defer out.Close()
err = apidocs.Emit(operations, out, apidocs.EmitOptions{
Title: "MyService API",
Version: "0.1.0",
Servers: []apidocs.Server{{URL: "http://localhost:8080"}},
// Zero SecurityScheme yields an http bearer JWT scheme; zero
// PermissionExtension yields x-teamusers-permission, which the
// VitePress renderer reads.
})
if err != nil {
panic(err)
}
}3. Optional: derived permission lines
If your service gates routes with path-derivable permission keys, pass a apidocs.PermissionDeriver to Collect instead of nil. The deriver returns an any-scoped key and an optional team-scoped alternative; both render as a Required permission line in the reference. teamusers' own deriver is cmd/genspec/main.go in this repository. Per-operation extras that are not path-derivable (step-up freshness, audience restrictions) belong in the operation's PermissionNote field, which renders as a suffix on the same line.
4. Git-ignore the output
docs/public/openapi.yaml is generated; add it to .gitignore and regenerate it on demand (see the predocs hooks below).
VitePress side
sh
pnpm add -D vitepress teamusers-apidocs-vitepressAdd the two dynamic-route stubs under docs/api/reference/:
ts
// docs/api/reference/[tag].paths.ts
import { renderApiReferencePaths } from 'teamusers-apidocs-vitepress'
export default {
paths: renderApiReferencePaths
}md
<!-- docs/api/reference/[tag].md -->
<!-- @content -->The loader reads docs/public/openapi.yaml relative to process.cwd() by default; pass specPath to createApiReferencePaths for other layouts. One page is generated per OpenAPI tag; write your own sidebar entries for /api/reference/ in docs/.vitepress/config.mts (the package ships content only, not navigation).
Wire regeneration into the docs scripts so the spec is always fresh:
jsonc
// package.json
{
"scripts": {
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"predocs:dev": "go run ./cmd/genspec",
"predocs:build": "go run ./cmd/genspec"
}
}The predocs:* hook runs automatically before the matching docs:* script. (Only the teamusers repository itself needs the extra pnpm --filter teamusers-apidocs-vitepress build step, because it consumes the package from the workspace instead of the registry.)
Checklist
go get github.com/crazy4chicken/nsc-teamusers/apidocs/go@v0.1.0DocOperationsnext to handlers;go run ./cmd/genspecexits zerodocs/public/openapi.yamlgit-ignoredpnpm add -D teamusers-apidocs-vitepress, two stub files, sidebar entriespnpm docs:buildrenders one page per tag, permission lines included
Best practices
Conventions that keep generated references readable and honest, distilled from internal/httpapi/doc.go:
- Summary is a label, Description is guidance. Keep summaries short ("List users", "Rotate the active signing key"). Start descriptions with "Use to/for/when ..." so the first sentence tells the reader which situation the endpoint serves, then document preconditions and contract details.
- Realistic examples. Response examples should use production-shaped values: ULID identifiers, RFC 3339 timestamps, real enum values. Readers copy them into fixtures.
- Enumerate errors. List every status the handler can return with a stable, machine-readable
code(clients switch oncode, not prose). Bearer-protected operations always include 401; permission-gated ones include 403. - Document POST idempotency. If the endpoint honors
Idempotency-Key, say so in the description with the retry semantics; if a mutation is naturally idempotent (PUT semantics), say that instead. - Spell out route-specific pagination details. Describe each list's cursor key, ordering, filters, and errors; link the REST pagination guide for shared limit, envelope, and terminal-cursor behavior instead of repeating it.
- Keep auth requirements structured. Fresh-auth (step-up) and similar route middleware requirements go in
PermissionNote, not in prose — the renderer keeps them on the Required permission line where readers look for them. - One tag per resource domain. Tags become reference pages; split domains (Users, Teams, Sessions) rather than dumping everything under one generic tag.
- Delete routes and metadata together. Pairing fails the generator when one side is removed without the other — that failure is the feature, not a nuisance; do not work around it.
- Write the spec atomically. Generate to a temporary file and rename into place (see
cmd/genspec/main.go), so a failed generation never leaves a truncated spec that the docs site then builds against.
CI deployment (GitHub Pages)
Automate the build so every merge publishes fresh docs. The workflow below mirrors teamusers' own .github/workflows/docs.yml; the Go toolchain is required because the predocs:build hook runs genspec:
yaml
name: Documentation
on:
push:
branches:
- main
paths:
- 'docs/**'
- 'cmd/genspec/**'
- 'internal/**' # doc.go metadata lives next to the handlers
- '.github/workflows/docs.yml'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
with: { version: 12.6.0 }
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with: { go-version-file: go.mod }
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with: { node-version: 24, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm docs:build
- uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
- uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with: { path: docs/.vitepress/dist }
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1Three things to wire outside the workflow:
- Pages source. Repository Settings → Pages → Build and deployment → Source: GitHub Actions (the
deploy-pagesaction owns publishing; nogh-pagesbranch is involved). - Base path. Project pages serve under
/<repo>/, so setbaseindocs/.vitepress/config.mts(teamusers uses/nsc-teamusers/) or links and assets 404. User/organization pages and custom domains serve from/and need nobase. - Trigger paths. The
paths:filter must cover everywhere operation metadata can change —docs/**, thegenspeccommand, and the packages holding your routers anddoc.gofiles — or doc updates silently skip deployment.
Pin actions by commit hash as shown; the hashes above match the versions teamusers runs in production.