Demonstration repo to show how swaggo library works
Here I provided a simple http server with several handlers. It works with the global array of items (imitation of database interaction) to mimic basic CRUD operations.
To start with you need to get a swaggo packagego install github.com/swaggo/swag/cmd/swag@latest
Unfortunately I could not access it directly from console as a regular util so I had to provide the absolute path to the app (I hope you won`t face this problem and your $PATH will work as intended so further I will to refer to this util as swag as it should be):
~/go/bin/swag --version
You also need http-swagger to register it in the handler
go get -u github.com/swaggo/http-swagger
NOTE: If you use web framework try to find the corresponding package from the list.
Swaggo is based on the declarative comments. You start with most basic API infromation e.g
- API version
- Project name
- Contact information
- Licence
- Host
- Root path
// @title Project Name // @version 0.0.1 // @host localhost:3000 // @BasePath / // @contact.name company_name // @contact.url http://www.link-to-support.io/support // @contact.email [email protected] func main(){ ... }
Then you need to provide docs for methods in a similar way:
// @title list godoc // @Summary list items // @Description list all items from global var // @Tags items // @Produce json // @Success 200 {object} []models.Item // @Router /list [get]โ func list(w http.ResponseWriter, r *http.Request){ ... }
Please refer to swaggo documentation for more available attributes.
NOTE: swaggo generaters models automatically, but you can also hide some fields by using fields attributes.
After you wrote your comments you can format them by calling:
swag fmt
Then you need to run
swag init
To generate docs files.
Finally you can run your server to check swagger works and shows data correctly. Run
go run .
and follow http://localhost:3000/swagger/.