This is a creation in Article, where the information may have evolved or changed.
Add swagger to it.
A good API's
, must be inseparable from a good API
document
To develop a purely handwritten API
document that does not exist: =)
Installing Swag
1. Go get
$ go get -u github.com/swaggo/swag/cmd/swag
If $GOPATH/bin
you do not join $PATH
, you need to perform a move of its executable file to the $GOBIN
next
mv $GOPATH/bin/swag /usr/local/go/bin
2, GOPM get
The package has a reference golang.org
on the package, if no scientific Internet, you can use GOPM to install
gopm get -g -v github.com/swaggo/swag/cmd/swagcd $GOPATH/src/github.com/swaggo/swag/cmd/swaggo install
In the same vein, move its executable file to the $GOBIN
next
Verify that the installation is successful
$ swag -vswag version v1.1.1
Installing Gin-swagger
$ go get -u github.com/swaggo/gin-swagger$ go get -u github.com/swaggo/gin-swagger/swaggerFiles
Note: Three packages have a certain size, installation needs to wait a while or to science online
Initialization
Write API comments
Swagger
You need to write the corresponding comments or annotations to the method, and then use the generator to automatically generate the description file
gin-swagger
An example is given:
// @Summary Add a new pet to the store// @Description get string by ID// @Accept json// @Produce json// @Param some_id path int true "Some ID"// @Success 200 {string} string "ok"// @Failure 400 {object} web.APIError "We need ID!!"// @Failure 404 {object} web.APIError "Can not find ID"// @Router /testapi/get-string-by-int/{some_id} [get]
We can refer Swagger
to the annotation specifications and examples to write
// @Summary 新增文章标签// @Produce json// @Param name query string true "Name"// @Param state query int false "State"// @Param created_by query int false "CreatedBy"// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"// @Router /api/v1/tags [post]func AddTag(c *gin.Context) {
// @Summary 修改文章标签// @Produce json// @Param id param int true "ID"// @Param name query string true "ID"// @Param state query int false "State"// @Param modified_by query string true "ModifiedBy"// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"// @Router /api/v1/tags/{id} [put]func EditTag(c *gin.Context) {
Referenced annotations are visible Gin-blog
Generated
We go to gin-blog
the project root directory and execute the initialization command
[$ gin-blog]# swag init2018/03/13 23:32:10 Generate swagger docs....2018/03/13 23:32:10 Generate general API Info2018/03/13 23:32:10 create docs.go at docs/docs.go
After completion, it will be generated under the project root directory.docs
docs/├── docs.go└── swagger ├── swagger.json └── swagger.yaml
We can examine the docs.go
variables in the file doc
, detailing the annotations and notes written in our document
Verify
You are done, visit http://127.0.0.1:8000/swagger/index.html
to see API
if the document is generated correctly
Reference
Sample code for this series