Go language uses swagger to generate interface documents

Time:2021-9-14

This article was first published on my personal blog: liwenzhou.com,More detailed practical content of the go language project is on liwenzhou.com.

Swagger generates interface documents

Introduction to swagger

Swagger is essentially an interface description language for describing restful APIs represented by JSON. Swagger works with a set of open source software tools to design, build, document, and use restful web services. Swagger includes automatic documentation, code generation, and test case generation.

In the project development process of front-end and back-end separation, if the back-end students can provide a clear interface document, it can greatly improve everyone’s communication efficiency and development efficiency. However, writing interface documents has always been a headache, and the maintenance of subsequent interface documents is also very energy-consuming.

It’s best to have a solution that can not only meet our needs for output documents, but also automatically update with code changes, and swagger is the kind of tool that can help us solve the problem of interface documents.

Taking the gin framework as an example, the gin swagger library is used to automatically generate restful API documents using swagger 2.0.

Gin swagger actual combat

Want to usegin-swaggerTo automatically generate interface documents for your code, you generally need the following three steps:

  1. Add declarative comments to the interface code as required by swagger. Refer to the format of declarative comments for details.
  2. Using swag tool to scan code and automatically generate API interface document data
  3. Rendering online interface document pages using gin swagger

Step 1: add notes

Write the introduction information about the project in the form of comments on the main function of the program entry.

package main

//@ Title write the title here
// @version 1.0
//@ description write description here
// @termsOfService http://swagger.io/terms/

//@ contact.name write contact information here
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

//@ host write the host of the interface service here
//@ basepath write base path here
func main() {
 r := gin.New()

 // liwenzhou.com ...

 r.Run()
}

The interface function (usually located in the controller layer) that handles the request in your code is annotated as follows:

//Getpostlisthandler2 upgraded post list interface
//@ summary upgraded post list interface
//@ description can sort and query the post list interface by community, time or score
//@ tags post related interface
// @Accept application/json
// @Produce application/json
//@ param authorization header string false "bearer user token"
//@ param object query models.parampostlist false "query parameters"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
// @Router /posts2 [get]
func GetPostListHandler2(c *gin.Context) {
 //Get request parameter (query string): / API / V1 / posts2? page=1&size=10&order=time
 //Specifying initial parameters when initializing a structure
 p := &models.ParamPostList{
  Page:  1,
  Size:  10,
  Order: models.OrderTime,
 }

 if err := c.ShouldBindQuery(p); err != nil {
  zap.L().Error("GetPostListHandler2 with invalid params", zap.Error(err))
  ResponseError(c, CodeInvalidParam)
  return
 }
 data, err := logic.GetPostListNew(p)
 //Get data
 if err != nil {
  zap.L().Error("logic.GetPostList() failed", zap.Error(err))
  ResponseError(c, CodeServerBusy)
  return
 }
 ResponseSuccess(c, data)
 //Return response
}

The parameter types in the above comments useobjectmodels.ParamPostListThe specific definitions are as follows:

// bluebell/models/params.go

//Parampostlist get post list query string parameter
type ParamPostList struct {
 Communityid Int64 ` JSON: "community_id" form: "community_id" ` // can be empty
 Page Int64 ` JSON: "page" form: "page" example: "1" ` // page number
 Size Int64 ` JSON: "size" form: "size" example: "10" ` // amount of data per page
 Order string ` JSON: "order" form: "order" example: "score" ` // sort by
}

The response data type is also usedobject, I’m used to defining one in the controller layerdocs_models.goFile to store the response data model used in the document.

// bluebell/controller/docs_models.go

// _ Responsepostlist post list interface response data
type _ResponsePostList struct {
 Code rescode ` JSON: "code" ` // business response status code
 Message string ` JSON: "message" ` // prompt message
 Data [] * models. Apipostdetail ` JSON: "data" ` // data
}

Step 2: generate interface document data

After writing the comments, install the swag tool using the following command:

go get -u github.com/swaggo/swag/cmd/swag

Execute the following command in the project root directory to generate interface document data using the swag tool.

swag init

After executing the above command, if the comment format you write is OK, there will be one more in your project root directorydocsfolder.

./docs
├── docs.go
├── swagger.json
└── swagger.yaml

Step 3: introduce gin swagger to render document data

Then, it is introduced in the following way where the route is registered in the project codegin-swaggerRelevant contents:

import (
 // liwenzhou.com ...

 _  "Bluebell / docs" // don't forget to import the docs generated in the previous step

 gs "github.com/swaggo/gin-swagger"
 "github.com/swaggo/gin-swagger/swaggerFiles"

 "github.com/gin-gonic/gin"
)

Register swagger API related routes

r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))

Run your project program and open the browser to access it http://localhost:8080/swagger/index.html You can see the swagger 2.0 API document.

gin_swagger文档gin_ Swagger documentation

gin-swaggerIt also providesDisablingWrapHandlerFunction to disable swagger by setting some environment variables. For example:

r.GET("/swagger/*any", gs.DisablingWrapHandler(swaggerFiles.Handler, "NAME_OF_ENV_VARIABLE"))

At this point, if the environment variableNAME_OF_ENV_VARIABLESet to any value, then/swagger/*anyA 404 response will be returned as if no route was specified.


This article was first published on my personal blog: liwenzhou.com,More detailed practical content of the go language project is on liwenzhou.com.