Introduction
Swag parses Go source code annotations written as structured comments and produces a complete Swagger 2.0 (OpenAPI) specification. Combined with middleware for Gin, Echo, Fiber, or Chi, it serves an interactive Swagger UI directly from your running Go application, keeping documentation in sync with the code.
What Swag Does
- Parses Go comment annotations into a Swagger 2.0 JSON/YAML spec
- Generates interactive Swagger UI served by your Go application
- Supports request/response models, query params, headers, and auth definitions
- Handles nested structs, enums, arrays, and custom types automatically
- Validates annotations at generation time to catch errors early
Architecture Overview
The swag init command walks the Go AST of your project, extracts specially formatted comments from handler functions, and builds an in-memory Swagger spec. It writes the spec as docs/swagger.json and a Go package that embeds the spec. At runtime, a framework-specific middleware (e.g., gin-swagger) serves the embedded spec through Swagger UI with no external file dependencies.
Self-Hosting & Configuration
- Install the CLI with
go install github.com/swaggo/swag/cmd/swag@latest - Add annotations above handler functions following the Swag comment format
- Run
swag initto regenerate docs after code changes - Configure base path, host, and schemes via general API annotations in main.go
- Use
--parseDependencyto include models from external packages
Key Features
- Zero-config generation from annotated Go comments
- Framework adapters for Gin, Echo, Fiber, Chi, and net/http
- Automatic model inference from Go struct tags
- Supports file upload, multipart form, and binary response types
- CI-friendly: run
swag initin your build pipeline to keep docs current
Comparison with Similar Tools
- go-swagger — full OpenAPI 2.0 toolkit but heavier; Swag focuses on annotation-driven generation
- oapi-codegen — generates Go code from an OpenAPI spec (spec-first); Swag is code-first
- Swagger Editor — manual spec editing; Swag derives the spec from source code
- Redoc — rendering-only; Swag handles both generation and serving
- grpc-gateway — targets gRPC services; Swag targets REST handlers
FAQ
Q: Does Swag support OpenAPI 3.0? A: Swag generates Swagger 2.0 specs. You can convert to OpenAPI 3.0 using tools like swagger2openapi.
Q: How do I document authentication?
A: Add @SecurityDefinitions annotations in main.go and reference them with @Security on each handler.
Q: Can Swag parse models from other packages?
A: Yes, use the --parseDependency flag to include structs defined in imported packages.
Q: Does it work with Go modules? A: Yes, Swag fully supports Go modules and resolves imports through the module graph.