Golang Swagger
by @samber
Golang OpenAPI/Swagger documentation with swaggo/swag — annotation comments (@Summary, @Param, @Success, @Router, @Security), swag init code generation, fram...
Three steps to get Swagger UI running:
swag init # generates docs/ with docs.go, swagger.json, swagger.yaml
swag init -g cmd/api/main.go # if general info is not in main.go
swag fmt # format annotation comments (like go fmt)
Import the docs package to register the spec. Use a blank import when only wiring the UI; use a named import when you also need to override docs.SwaggerInfo at runtime:
import _ "yourmodule/docs" // blank: registers spec, no identifier
import docs "yourmodule/docs" // named: use when overriding SwaggerInfo
Wire the UI endpoint — pick your framework:
// Gin
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))// Echo
e.GET("/swagger/*", echoSwagger.WrapHandler)
// Fiber
app.Get("/swagger/*", fiberSwagger.WrapHandler(swaggerFiles.Handler))
// net/http
mux.Handle("/swagger/", httpSwagger.Handler(swaggerFiles.Handler))
// Chi
r.Get("/swagger/*", httpSwagger.Handler(swaggerFiles.Handler))
Access the UI at /swagger/index.html.
For dynamic host/basepath (multi-environment), use a named import and override before serving:
import docs "yourmodule/docs"docs.SwaggerInfo.Host = os.Getenv("API_HOST")
docs.SwaggerInfo.BasePath = "/api/v1"
clawhub install golang-swagger