Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

A background

Side projects before, during, and after a restful interface docking, need to have a clear interface documentation, at this time alone to interfaces written documents, time-consuming, cut after the code changes, also need maintenance interface documentation, prone to do not have a unified document at this time, the interface documentation to write directly in the code is a better way.

Swagger solves this problem. Developers simply write Swagger comments when writing interface code according to a specific specification, and use Swagger to generate interface documentation.

Introduction to Swagger UI

Swagger is an API generation tool that generates documentation. Swagger is documented by writing YAML and JSON. And can be tested and other work.

By Swagger, interface documents can be easily generated to facilitate the front end to view and test.

Iii Project Integration

3.1 installation swag

$ go get github.com/swaggo/swag/cmd/swag
Copy the code

3.2 Generating Files

Related files are generated for the first time, code has been modified later, and swaG annotations have been added

#In the directory of the Go project (including main.go), use the swag init command to generate the relevant files.
$ swag init
2021/09/23 16:32:23 Generate swagger docs....
2021/09/23 16:32:23 Generate general API Info, search dir:./
2021/09/23 16:32:26 create docs.go at docs/docs.go
2021/09/23 16:32:26 create swagger.json at docs/swagger.json
2021/09/23 16:32:26 create swagger.yaml at docs/swagger.yaml

Copy the code

3.3 installation gin – swagger

$ go get -u github.com/swaggo/gin-swagger
$ go get -u github.com/swaggo/gin-swagger/swaggerFiles
Copy the code

3.4 integration

  • Import the generated Docs package
  • Write the interface description according to the specification SWAG on the specific interface
  • Import packets from routes
  • Execute swag init again to update the interface
  • Run after application, the browser visit: http://localhost:8887/swagger/index.html
package main import ( "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" _ "github.com/swaggo/gin-swagger/example/basic/docs" // docs is generated by Swag CLI, You have to import it.) // @title Swagger Example API // @version 1.0 // @description This is a sample Server Petstore server. // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url HTTP: / / http://www.swagger.io/support / / @ contact. Email [email protected]. / / @ license name Apache 2.0 / / @ license. Url HTTP: / / http://www.apache.org/licenses/LICENSE-2.0.html / / @ host petstore. Swagger. IO / / @ BasePath/v2 func main () {r: = gin.New() url := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) r.Run() }Copy the code

Four Different types

4.1 the request

4.4.1 url parameter

// @param id path int true "id" Parameter type [query(? Id =),path(/123)]; Data type; The required; Parameter Description)
Copy the code

4.1.2 body parameters

For example json

// @param data body models.RegistryAuth true
Copy the code

4.2 return

2 string

// @Success 200 {string} json "{"msg":"ok"}"
Copy the code

4.2.2 Structure Return

// @failure 400 {object} models.ResponseErr "Error" // @failure 500 {object} models.ResponseErr "Internal error"Copy the code

Five practical

5.1 Main Function Adds the global function

// @title smartkm_api_image Swagger Example
/ / @ version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @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 petstore.swagger.io
// @BasePath /
func main(a) {
	// Start the service
	run()
}

Copy the code

5.2 Function Levels

5.2.1 Get request

// @summary View the details of the migration task
// @description Displays detailed information about the migration task
// @Accept json
// @Produce json
// @Param task_id path string true "task_id"
// @success 200 {object} models.Response"
// @failure 400 {object} models.ResponseErr "Error"
// @failure 500 {object} models.ResponseErr "Error"
// @Router /task [get]
Copy the code

5.2.2 Post request

// @summary Creates an image migration task
// @description Creates an image migration task
// @Accept json
// @Produce json
// @param data body models.CreateTaskReq true
// @success 200 {object} models.Response"
// @failure 400 {object} models.ResponseErr "Error"
// @failure 500 {object} models.ResponseErr "Error"
// @Router /task [post]
Copy the code

5.2.3 requires the Delete request

// @summary Deletes the image migration task
// @description Deletes the image migration task
// @Accept json
// @Produce json
// @param data body models.TaskReq true
// @success 200 {object} models.Response"
// @failure 400 {object} models.ResponseErr "Error"
// @failure 500 {object} models.ResponseErr "Error"
// @Router /task [delete]
Copy the code

Matters needing attention

  • When routing to add Swagger, you need to import the project-generated Docs package
  • Func: func: func: funC: funC: funC: funC: funC: funC: funC: funC: funC: funC
  • Error 404 Page not found when accessing swagger console because no route for Swagger is added
  • “Failed to load spec” : Failed to import swagger docs folder

Refer to the link

  • Studygolang.com/articles/12…
  • Github.com/go-swagger/…
  • Github.com/swaggo/gin-…