Swagger is introduced

Swagger is essentially an interface description language for describing RESTful apis expressed using JSON. Swagger works with a suite of open source software tools to design, build, document, and use RESTful Web services. Swagger includes automated documentation, code generation, and test case generation.

In the process of project development with the separation of the front and back ends, if the backend students can provide a clear interface document, it will greatly improve the efficiency of communication and development. But interface documentation has historically been a pain in the neck, and the subsequent maintenance of interface documentation can be very taxing.

It would be nice to have a solution that both satisfies our need for output documentation and automatically updates the code as it changes, and Swagger is the tool that can help us solve our interface documentation problems.

Using the GIN framework as an example, the GIN-Swagger library is used to automatically generate RESTful API documents using Swagger 2.0.

Gin – swagger of actual combat

To automatically generate interface documentation for your code using Gin-Swagger, the following three steps are generally required:

  1. Add declarative comments to interface code according to Swagger’s requirements, refer to declarative comment format.
  2. Use the SWAG tool to scan code to automatically generate API interface document data
  3. Render the online interface document page with gin-Swagger

Step 1: Add comments

Write the project information in comments on the program entry main function.

package main



// @title

/ / @ version 1.0

// @description writes the description

// @termsOfService http://swagger.io/terms/



// @contact.name specifies the contact information

// @contact.url http://www.swagger.io/support

// @contact.email [email protected]



/ / @ license. Name the Apache 2.0

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



// @host specifies the host of the interface service

// @basepath say base path

func main(a) {

 r := gin.New()



 // liwenzhou.com ...



 r.Run()

}

Copy the code

Comment the interface functions that handle requests in your code (usually in the Controller layer) as follows:

// GetPostListHandler2 updated post list interface

// @summary updated post list interface

// @description Can query the post list interface by community time or score

// @tags posts related interface

// @Accept application/json

// @Produce application/json

// @param Authorization Header string false "Bearer of user tokens"

// @param object query models.ParamPostList false

// @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

 // Specify the initial parameters when initializing the structure

 p := &models.ParamPostList{

  Page:  1.

  Size:  10.

  Order: models.OrderTime,

 }



 iferr := 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

 iferr ! =nil {

  zap.L().Error("logic.GetPostList() failed", zap.Error(err))

  ResponseError(c, CodeServerBusy)

  return

 }

 ResponseSuccess(c, data)

 // Return the response

}

Copy the code

The above comment uses object as the parameter type. Models.ParamPostList is defined as follows:

// bluebell/models/params.go



// ParamPostList Gets the post list query string parameter

type ParamPostList struct {

 CommunityID int64  `json:"community_id" form:"community_id"`   // Can be null

 Page        int64  `json:"page" form:"page" example:"1"`       / / page

 Size        int64  `json:"size" form:"size" example:"10"`      // Data volume per page

 Order       string `json:"order" form:"order" example:"score"` // Sort by

}

Copy the code

The response data type also uses object. I personally define a docs_models.go file in the Controller layer to store the response data models used in the document.

// bluebell/controller/docs_models.go



// _ResponsePostList Post list interface response data

type _ResponsePostList struct {

 Code    ResCode                 `json:"code"`    // Service response status code

 Message string                  `json:"message"` // Prompt message

 Data    []*models.ApiPostDetail `json:"data"`    / / data

}

Copy the code

Step 2: Generate interface document data

After writing the comments, use the following command to install the Swag tool:

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

Copy the code

Use the SWAg tool to generate interface document data by executing the following command in the project root directory.

swag init

Copy the code

After executing this command, if your comments are formatted correctly, you will have a docs folder in your project root.

./docs

├ ─ ─ docs. Go

├ ─ ─ swagger. Json

└ ─ ─ swagger. Yaml

Copy the code

Step 3: Introduce gin-Swagger render document data

Gin-swagger is then introduced in the project code where routes are registered as follows:



import (

 // liwenzhou.com ...



 _ "bluebell/docs"  // Don't forget to import the docs you generated in the previous step



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

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



 "github.com/gin-gonic/gin"

)

Copy the code

Register swagger API – related routes

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

Copy the code

Put your project program to run, open a browser to http://localhost:8080/swagger/index.html can see Swagger 2.0 Api documentation.

Gin_swagger document

Gin-swagger also provides the DisablingWrapHandler function to disable Swagger by setting certain environment variables. Such as:

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

Copy the code

If NAME_OF_ENV_VARIABLE is set to any value, /swagger/*any will return a 404 response, just as if no route was specified.


This post started on my personal blog: liwenzhou.com

For more detailed go Web development video courses, please click on the picture in the upper right corner of the blog.