πŸ“š godoclive - Awesome Go Library for Utilities

Go Gopher mascot for godoclive

Generates interactive API documentation from Go HTTP handlers using static analysis of chi, gin, and net/http routers

🏷️ Utilities
πŸ“‚ Utilities
⭐ 0 stars
View on GitHub πŸ”—

Detailed Description of godoclive

GoDoc Live

API documentation that writes itself.
Point it at your Go code. Get interactive docs. No annotations required.

CI Go Report Card Go Reference Release License: MIT Codecov

GoDoc Live demo

Your API docs are already in your code. GoDoc Live just reads them.

GoDoc Live uses go/ast and go/types β€” the same packages the Go compiler uses β€” to walk your source, extract every route, parameter, request body, response type, and auth pattern, then generates an interactive docs site and OpenAPI 3.1.0 spec. No YAML to maintain. No annotations to add. No code to change.

Quickstart

go install github.com/syst3mctl/godoclive/cmd/godoclive@latest
godoclive generate ./...
open docs/index.html

Or serve with live reload β€” docs update as you save:

godoclive watch --serve :8080 ./...

Why GoDoc Live?

API docs written by hand drift. Someone adds a query param and forgets the spec. Someone changes a status code and the YAML still says 200. Six months later your docs and your code contradict each other.

GoDoc Live has no drift problem β€” it reads the source of truth directly.

GoDoc LiveSwagger annotationsManual OpenAPI
Setupgo installAdd annotations to every handlerWrite YAML by hand
Stays in syncAlwaysOnly if you update annotationsOnly if you update YAML
Code changes requiredNoneYesNo
Works on existing codeYesPartialNo

What It Detects

FeatureDescription
RoutesHTTP methods and path patterns from router registrations
Path ParamsType inference from name heuristics ({id} β†’ uuid, {page} β†’ integer) and handler body analysis
Query ParamsRequired/optional detection, default values from DefaultQuery
Request BodyStruct extraction from json.Decode / c.ShouldBindJSON with full field metadata
ResponsesStatus codes paired with response body types via branch-aware analysis
File UploadsMultipart detection from r.FormFile / c.FormFile
Helper TracingOne-level tracing through respond(), writeJSON(), sendError() wrappers
Auth DetectionJWT bearer, API key, and basic auth from middleware body scanning
Auto NamingSummaries and tags inferred from handler names (GetUserByID β†’ "Get User By ID")

UI Features

Environment URL Switcher

A dropdown in the topbar lets you switch base URLs on the fly β€” curl snippets and the Try It panel update immediately. Define environments in .godoclive.yaml:

openapi:
  servers:
    - url: "http://localhost:8080"
      description: "Local"
    - url: "https://staging-api.example.com"
      description: "Staging"
    - url: "https://api.example.com"
      description: "Production"

If no servers are configured, a single Default entry is created from --base-url. The selected URL persists across page refreshes via localStorage. A pencil button lets you type a fully custom URL at any time.

Client-Side Route Visibility

Hide individual endpoints directly from the sidebar β€” useful when you want to focus on a subset of routes without permanently excluding them from the source.

  • Hover any sidebar row β†’ an eye icon appears
  • Click it β†’ the endpoint disappears from the sidebar and content area
  • The sidebar footer shows Show N hidden β€” click to reveal hidden routes dimmed in place
  • Click the eye-off icon on a revealed route to unhide it
  • Hidden state is keyed by "METHOD /path" and persisted in localStorage, surviving page refreshes and doc regeneration

Supported Routers

RouterStatusFeatures
chi (go-chi/chi/v5)DoneRoute, Group, Mount, inline handlers
gin (gin-gonic/gin)DoneGroups, Use chains, ShouldBindJSON
net/http (Go 1.22+ stdlib)Done"METHOD /path" patterns, r.PathValue(), http.Handler
gorilla/mux (gorilla/mux)DoneHandleFunc().Methods(), PathPrefix().Subrouter(), mux.Vars(), regex params
echo (labstack/echo/v4)DoneGroups, Use chains, c.Bind(), c.QueryParam(), c.JSON(), c.NoContent()
fiber (gofiber/fiber/v2)DoneGroups, Use chains, c.BodyParser(), c.Query(), c.Params(), c.Status().JSON(), c.SendStatus()

CLI Reference

godoclive generate [packages]

godoclive generate ./...
godoclive generate --output ./api-docs --theme dark ./...
godoclive generate --format single ./...         # Single self-contained HTML (~300KB)
godoclive generate --serve :8080 ./...           # Generate + serve
godoclive generate --openapi ./openapi.json ./... # Also emit OpenAPI 3.1.0 spec
FlagDefaultDescription
--output./docsOutput directory
--formatfolderfolder (separate files) or single (one self-contained HTML)
--titleautoProject title displayed in docs
--base-urlβ€”Pre-fill base URL in Try It
--themelightlight or dark
--serveβ€”Start HTTP server after generation (e.g., :8080)
--openapiβ€”Also generate an OpenAPI 3.1.0 spec at the given path (.json or .yaml)

godoclive analyze [packages]

Run analysis and print a contract summary to stdout.

godoclive analyze ./...
godoclive analyze --json ./...        # Machine-readable output
godoclive analyze --verbose ./...     # Show unresolved details
FlagDefaultDescription
--jsonfalseOutput as machine-readable JSON
--verbosefalseShow full unresolved list per endpoint

godoclive openapi [packages]

Generate an OpenAPI 3.1.0 specification without the HTML docs.

godoclive openapi ./...                          # Outputs ./openapi.json
godoclive openapi --output ./api.yaml ./...      # YAML format (inferred from extension)
godoclive openapi --server https://api.example.com ./...
FlagDefaultDescription
--output./openapi.jsonOutput file path (.json or .yaml)
--formatautojson or yaml β€” inferred from file extension if omitted
--titleautoAPI title in the spec info block
--serverβ€”Server URL to include in the servers array

godoclive watch [packages]

Watch for .go file changes and regenerate docs automatically. Supports the same flags as generate.

godoclive watch --serve :8080 ./...

When --serve is set, the browser auto-reloads via Server-Sent Events β€” edit your code, save, see updated docs instantly.

godoclive validate [packages]

Report analysis coverage β€” what percentage of endpoints are fully resolved.

godoclive validate ./...
godoclive validate --json ./...
FlagDefaultDescription
--jsonfalseOutput as JSON
--verbosefalseShow full unresolved list per endpoint

Ignoring Routes

//godoclive:ignore directive

Add a //godoclive:ignore (or //godoclive:skip) comment directly in your source to permanently exclude a route from all output β€” HTML docs, OpenAPI spec, and analysis. The route is filtered at extraction time and never enters the pipeline.

//godoclive:ignore
r.Get("/debug/pprof", pprof.Index)

r.Post("/internal/webhook", webhookHandler) //godoclive:ignore

Both placement styles are supported:

  • Preceding line β€” comment on the line immediately above the route registration
  • Trailing comment β€” comment on the same line as the route registration

The directive works across all supported routers (chi, gin, gorilla/mux, echo, fiber, net/http stdlib).

For pattern-based exclusion (e.g. all routes matching GET /internal/*), use the exclude field in .godoclive.yaml instead.

Configuration

.env file

Create a .env file in your project root to set the API base URL for the Try It panel:

API_URL="http://localhost:8080"

Precedence: --base-url CLI flag > .env API_URL > .godoclive.yaml base_url > default.

.godoclive.yaml

Create an optional .godoclive.yaml in your project root:

# Project metadata
title: "My API"
version: "v2.1.0"
base_url: "https://api.example.com"
theme: "dark"

# Exclude endpoints by pattern (glob on "METHOD /path")
# Use //godoclive:ignore in source for per-route exclusion instead.
exclude:
  - "GET /internal/*"
  - "* /debug/*"

# Override or supplement analysis results
overrides:
  - path: "POST /users"
    summary: "Register a new user account"
    tags: ["accounts"]
    responses:
      - status: 409
        description: "Email already registered"
      - status: 503
        description: "Service temporarily unavailable"

# Auth configuration
auth:
  header: "Authorization"
  scheme: "bearer"

# OpenAPI 3.1.0 spec metadata
openapi:
  description: "Full description of the API."
  contact:
    name: "API Support"
    url: "https://example.com/support"
    email: "[email protected]"
  license:
    name: "MIT"
    url: "https://opensource.org/licenses/MIT"
  servers:
    - url: "https://api.example.com"
      description: "Production"
    - url: "https://staging.example.com"
      description: "Staging"

Zero configuration is always valid β€” the tool produces useful output without any config file.

How It Works

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  1. Load  │──▢│2. Detect │──▢│3. Extract│──▢│4. Resolveβ”‚
β”‚ go/pkgs   β”‚   β”‚ chi/gin  β”‚   β”‚  routes  β”‚   β”‚ handlers β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                    β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”
β”‚8.Generate│◀──│ 7. Auth  │◀──│ 6. Map   │◀──│5.Contractβ”‚
β”‚ HTML/CSS β”‚   β”‚ middlewareβ”‚   β”‚ structs  β”‚   β”‚params/bodyβ”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  1. Load β€” Uses go/packages to load and type-check your Go source code
  2. Detect β€” Identifies the router framework (chi, gin, gorilla/mux, echo, fiber, or stdlib) from imports
  3. Extract β€” Walks main() and init() AST to find route registrations
  4. Resolve β€” Resolves handler expressions to function declarations
  5. Contract β€” Extracts path params, query params, headers, body, and responses from handler ASTs
  6. Map β€” Converts types.Type into recursive TypeDef with JSON tags, examples, and field metadata
  7. Auth β€” Scans middleware function bodies for authentication patterns
  8. Generate β€” Transforms endpoint contracts into an interactive HTML documentation site

All analysis uses go/ast and go/types β€” no runtime reflection, no annotations, no code generation.

Programmatic API

Use GoDoc Live as a library in your own tools:

import "github.com/syst3mctl/godoclive"

// Analyze a project
endpoints, err := godoclive.Analyze(".", "./...",
    godoclive.WithTitle("My API"),
)

// Generate HTML docs
err = godoclive.Generate(endpoints,
    godoclive.WithOutput("./api-docs"),
    godoclive.WithFormat("single"),
    godoclive.WithTheme("dark"),
)

// Generate HTML docs + OpenAPI spec in one call
err = godoclive.Generate(endpoints,
    godoclive.WithOutput("./api-docs"),
    godoclive.WithOpenAPIOutput("./openapi.json"),
)

// Generate only an OpenAPI 3.1.0 spec (returns JSON bytes)
specBytes, err := godoclive.GenerateOpenAPI(endpoints,
    godoclive.WithTitle("My API"),
    godoclive.WithVersion("v2.1.0"),
)

Accuracy (Phase 1)

Measured across 12 testdata projects with 50 endpoints:

FeatureAccuracyTarget
Route detection100% (50 endpoints)95%
Path params100% (50 endpoints)99%
Query params100% (50 endpoints)85%
Response status codes100% (50 endpoints)85%
Auth detection100% (50 endpoints)87%

Performance

Benchmarks run on Apple M2 Pro, Go 1.25, using the testdata projects included in the repository. Run them yourself: go test -bench=. -benchmem ./internal/pipeline/ ./internal/generator/

Analysis pipeline

BenchmarkRoutesTimeMemory
LoadPackages (chi-basic)β€”~426 ms572 MB / 5.9 M allocs
RunPipeline chi-basic6~429 ms572 MB / 5.9 M allocs
RunPipeline gorilla-basic8~429 ms552 MB / 5.7 M allocs
RunPipeline gin-basic5~538 ms840 MB / 8.7 M allocs

The dominant cost is go/packages type-checking β€” loading and type-checking the full dependency tree via NeedDeps. Route extraction, contract analysis, struct mapping, and type lookups together add less than 5 ms on top. Memory is not retained after the call; it is held only during analysis and released when the returned []EndpointDef is in scope.

The type-lookup path was optimised in v0.1.0: a single packages.Visit traversal builds a pkgPath β†’ name β†’ types.Type index at pipeline start, replacing the previous O(NΓ—routesΓ—deps) repeated traversals with O(1) map lookups.

Documentation generation

BenchmarkEndpointsTimeMemory
Generate folder mode6~1.6 ms317 KB / 190 allocs
Generate single mode6~1.0 ms3.2 MB / 173 allocs

Single-file mode writes more memory (β‰ˆ10Γ— more per run) because all CSS, JS, and WOFF2 font assets are base64-encoded and inlined into one self-contained HTML file (~300 KB on disk).

Roadmap

PhaseScopeStatus
1chi + gin + net/http stdlib + gorilla/mux, full contract extraction, helper tracing, interactive docs UIDone
2OpenAPI 3.1.0 export (openapi command + --openapi flag)Done
2bechoDone
2cfiberDone
2dEnvironment URL switcher, client-side route visibility toggle, //godoclive:ignore directiveDone
3VS Code extension, GitHub Action integrationPlanned
4Multi-service gateway view, API version diffPlanned

Contributing

See CONTRIBUTING.md for guidelines on adding new router extractors, structuring testdata, and running the test suite.

License

MIT β€” see LICENSE.


Made with love and go/ast