swa is a CLI development tool designed to make working with Swaggo comments easy in Go projects. It analyzes your Go source code and automatically generates or updates Swaggo annotations for your API endpoints.
It also includes utilities for managing routing code, specifically generating Routes() methods on controllers.
Before swa gen |
After swa gen |
|---|---|
type Product struct {
Id string `json:"id"`
Title string `json:"title"`
}
func (c *ProductsController) GetProduct(ctx *gin.Context) {
id := ctx.Param("id")
// ... fetch product
ctx.JSON(200, product)
} |
type Product struct {
Id string `json:"id"`
Title string `json:"title"`
}
// GetProduct
// @Summary Get Product
// @Description Get Product
// @Tags Products
// @Accept json
// @Produce json
// @Param id path string true "id"
// @Success 200 {object} Product
// @Router /products/{id} [get]
func (c *ProductsController) GetProduct(ctx *gin.Context) {
id := ctx.Param("id")
// ... fetch product
ctx.JSON(200, product)
} |
flowchart TD
%% Main CLI
CLI(swa CLI Tool)
%% swa gen flow
GenCmd[\swa gen\]
CLI --> GenCmd
ParseAst[Parse Go AST]
GenCmd --> ParseAst
DetectHandlers{Detect Framework Handlers: Gin, Echo, Goravel, GoFr, NetHttp}
ParseAst --> DetectHandlers
GenerateSwaggo[Extract Context & Generate Annotations: @Summary, @Router, @Param, etc.]
DetectHandlers --> GenerateSwaggo
InjectDocs[Inject Comments into Source Code]
GenerateSwaggo --> InjectDocs
%% swa add:route flow
AddRouteCmd[\swa add:route\]
CLI --> AddRouteCmd
AnalyzeControllers[Scan Controller Files]
AddRouteCmd --> AnalyzeControllers
CheckRoutesMethod{"Has Routes() Method?"}
AnalyzeControllers --> CheckRoutesMethod
InjectRoutesMethod["Inject Boilerplate Routes() scope"]
CheckRoutesMethod -- No --> InjectRoutesMethod
BindEndpoints[Scan @Router tags & Bind Endpoints to Router]
CheckRoutesMethod -- Yes --> BindEndpoints
InjectRoutesMethod --> BindEndpoints
swa natively parses route definitions and handlers for the following standard libraries and web frameworks:
- Standard Library:
net/http - Gin:
github.com/gin-gonic/gin - Echo:
github.com/labstack/echo - Goravel:
github.com/goravel/goravel - Iris:
github.com/kataras/iris - GoFr:
gofr.dev
You can install the latest release directly via Go:
go install github.com/zerolethanh/swa@latestAlternatively, you can clone the repository and install it locally:
go install .The gen command analyzes your Go source code and generates Swaggo comments for your API endpoints. By default, it runs in a dry-run mode. To actually write the changes to your files, use the --write flag.
- Parses Go Code: Uses Go's
go/astto build an Abstract Syntax Tree of your files. - Detects Handlers: Identifies endpoint handlers matching known web frameworks (Gin, Echo, Iris, Goravel, GoFr,
net/http). - Generates Annotations: Extracts HTTP methods, paths, and parameter structures to construct compliant Swaggo comments (
// @Summary,// @Router, etc.). - Injects Comments: Prepends the generated annotations directly into your source code.
Usage:
swa gen --path <file_or_directory> [flags]Common Flags:
-p, --path string: Path to a.gofile or a directory to generate Swaggo comments for (Required)-w, --write: Write the generated comments directly to the files (default isfalse)-d, --dry: Perform a dry run without writing to files (default istrue)--walkDir: Walk all controllers in the directory. Autotrueif--pathpoints to a directory.--update: Update existing Swaggo comments by re-generating them-e, --excludes string: Comma-separated list of functions to exclude-s, --src string: Source file to generate from-r, --routesPrefix string: Prefix for the generated routes (e.g.,v1)--pureForm: Extract form props and add Swaggo lines instead of auto-detecting the form struct--reset: Remove all Swaggo lines except for@Summary,@Description, and the title line-v, --verbose: Show verbose output with full diff-m, --makeFuncDecl: Shift func-type to func-declaration--report: Write a report file to theswa-reportsfolder--updateMainFunc: Generatefunc main()Swaggo lines (default istrue)
Generates and inserts a func(r *Controller) Routes() method stub into your controller source files to assist with routing boilerplate.
- Scans Controllers: Looks for controller structs within the designated path.
- Generates
Routes()Method: Validates if aRoutes(baseRouter route.Router)method exists. If absent, it injects boilerplate Go code to provide a singleton pattern and theRoutesmethod scope. - Binds Endpoints: Scans existing Swaggo
@Routercomments within the controller to append the auto-generated route registration code.
Usage:
swa add:route --path <file_or_directory> [flags]Flags:
-p, --path string: File or directory to generate routes for (Required)--walk: Walk the directory to add routes (autotrueif--pathis a directory)-e, --exclude-paths strings: Paths to exclude from generation--reset: Routes reset task only--withReset: Reset the routes block then append routes
Contributions, issues, and feature requests are welcome! If you encounter any problems, bugs, or have ideas for improvements, please feel free to open an issue or submit a pull request. Your feedback is highly appreciated!
