This is the 29th day of my participation in the More Text Challenge. For more details, see more Text Challenge
If ❤️ my post is helpful, please comment, follow, or like. This is the greatest encouragement for me to continue my technical creation. More past posts are on my personal blog
Gin generates Swagger documents
Environment introduction
- Development environment: Windows10 X64
- Golang: 1.16
- Gin: 1.7.0
Install the Swagger
Since I have assumed that you have installed the GIN framework, I installed the Swag dependency directly in the project root directory
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
go get -u github.com/alecthomas/template
Copy the code
Call method comments
Swagger Documentation is generated by scanning a program file for method comments. So add a canonical comment to the method, which is a key Swagger standard comment
// AdminLogin godoc
// @summary Administrator login
// @description Administrator login
// @tags Administrator interface
// @ID /admin_login/login
// @Accept json
// @Produce json
// @param body body dto.AdminLoginInput true "body" #
// @Success 200 {object} middleware.Response{data=dto.DemoInput} "success"
// @Router /admin_login/login [post]
func (adminlogin *AdminLoginController) AdminLogin(ctx *gin.Context) {
// Define the incoming data structure
params:=&dto.AdminLoginInput{}
iferr:=params.BindValidParam(ctx); err ! =nil {
middleware.ResponseError(ctx, 1001, err)
return
}
out:=&dto.AdminLoginOutput{Token:params.UserName}
middleware.ResponseSuccess(ctx,out)
}
Copy the code
Swagger set to Gin Router
File the router/route. Go
# Load dependenciesimport (
"[Project name]/docs"
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
)
func InitHttpServer(a) {
var router *gin.Engine
router = gin.Default()
router.Static("/html"."./public")
// Set the Swagger access route
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
router.Run(":" + _const.HTTP_SERVER_PORT)
}
Copy the code
Swagger generates API documentation
In the project root directoryThe command line
Execute the commandswag init
swag init
This command generates a folder in the project root directorydocs
.
Access swagger to generate documentation
Project root Run the commandgo run main.go
Start the network service. See your GIN Settings service port, use the browser to accesshttp://localhost:[Set port]/swagger/index.html
You can see the interface document you just generated