go-swagger
API documentation with swaggo/swag. Covers annotations, security definitions, and generating OpenAPI specifications from Go code.
SKILL.mdskills/go/go-swagger/SKILL.md
GitHubCore Tool: swaggo/swag
swaggo/swag converts Go annotations into Swagger 2.0 (OpenAPI 2.0) documentation.
Workflow
- Add annotations to your API handlers and
main.go. - Run
swag initto generate thedocs/directory. - Import the generated
docspackage with a blank import inmain.go. - Serve the Swagger UI using a middleware (e.g.,
http-swagger,gin-swagger,echo-swagger).
Essential Annotations
General Info (in main.go)
// @title My Awesome API
// @version 1.0
// @description This is a sample server celler server.
// @host localhost:8080
// @BasePath /api/v1
Endpoint Definition
// @Summary Get user by ID
// @Description Retrieves a user's profile information by their unique identifier.
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "User ID"
// @Success 200 {object} model.User
// @Failure 404 {object} api.ErrorResponse
// @Router /users/{id} [get]
func GetUser(w http.ResponseWriter, r *http.Request) { ... }
Security Definitions
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
Apply to an endpoint:
// @Security Bearer
Struct Tags
Enrich your models with example, enums, and format tags:
type User struct {
ID string `json:"id" example:"user_123"`
Role string `json:"role" enums:"admin,user" example:"user"`
Email string `json:"email" format:"email"`
}
Best Practices
- Keep it Fresh — Run
swag initafter every change to your API annotations. - Blank Import — Ensure
_ "github.com/my/project/docs"is in yourmain.goso the UI loads the correct spec. - Use Structs for Body Params — Never use primitive types for
@Param body. Create a dedicated request struct instead. - Group by Tags — Use
@Tagsto group related endpoints in the Swagger UI. - Secure the UI — Disable the Swagger UI in production or protect it behind authentication.
Anti-patterns
- ❌ Stale Documentation — Forgetting to run
swag initleads to docs that don't match the code. - ❌ No Security Definitions — Testers can't use the "Authorize" button in Swagger UI.
- ❌ Unclear Error Responses — Not documenting
@Failurecodes makes the API hard to integrate with. - ❌ Implicit Types — Relying on swag to guess types for complex fields. Use
swaggertypeto be explicit. - ❌ Hardcoded Host — Don't hardcode
@hostif the API runs in multiple environments; use relative paths or environment variables.