Gin integrates swagger to build api documentation

Gin integrates swagger to build api documentation

Official document

Specific steps are as follows:

installation swag

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

Install gin-swagger

go get -u github.com/swaggo/gin-swagger

go get -u github.com/swaggo/gin-swagger/swaggerFiles

Example main.go

package main

import (
    _ "demo/docs"
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
    "net/http"
)

func main() {

    r := gin.Default()
    r.POST("/login", login)
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run(":8282")
}


//@log in
//@Description login
//@Accept json
//@Produce json
//@Param username path string true "username"
//@Param passwd path string true "passwd"
//@Success 200 {string} string "ok"
//@Router/login [post]
func login(c *gin.Context){
    username := c.PostForm("username")
    passwd := c.PostForm("passwd")
    c.String(http.StatusOK, "Hello world "+username+"_"+passwd)
}

Generate documentation

Execute in the project directory

swag init

At this time, you will find that a new docs directory has been created in the project directory, including docs.go, swagger.json, swagger.yaml

Run the sample program

go run main.go

View interface documentation

enter http://127.0.0.1:8282/swagger/index.html

Reference: https://cloud.tencent.com/developer/article/1706234 gin integrate swagger to build api documentation-Cloud + Community-Tencent Cloud