The official explanation is very clear, let me translate it here
[official github] ( swaggo/gin-swagger: gin middleware, using Swagger 2.0 to automatically generate RESTful API documents. (github.com) )
gin-swagger role
gin middleware, using Swagger 2.0 to automatically generate RESTful API documents, front-end and back-end interactive documents, to prevent nonsense
use
- Download Swag for Go using :
go get -u github.com/swaggo/swag/cmd/swag
As of Go 1.17, the installer executable is deprecated. can be used instead:go get``go install
go install github.com/swaggo/swag/cmd/swag@latest
- Run Swag at your Go project root path (for example), Swag willParse the annotations and generate the required files (folders and ) in the .
~/root/go-project-name``docs``docs/doc.go``~/root/go-project-name/docs
swag init
- Download gin-swagger using :
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
Import the following in your code:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
- Comment on the api according to the specified comment rules. The complete code and folder relationship are as follows:
package main
import (
"github.com/gin-gonic/gin"
docs "github.com/go-project-name/docs"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"net/http"
)
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(g *gin.Context) {
g.JSON(http.StatusOK,"helloworld")
}
func main() {
r := gin.Default()
docs.SwaggerInfo.BasePath = "/api/v1"
v1 := r.Group("/api/v1")
{
eg := v1.Group("/example")
{
eg.GET("/helloworld",Helloworld)
}
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
r.Run(":8080")
}
Demo project tree, run in relative positionswag init``.
.
├── docs
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── go.mod
├── go.sum
└── main.go
- Build your application, then go to http://localhost:8080/swagger/index.html and you'll see your Swagger UI.
annotation rules
- title is required. The title of the application. @title swagger API
- version is required. Provides the version of the application API. @version 1.0|
- description A short description of the application. @description This is a sample server unit server.
- tag.name The name of the tag. @tag this is the name of the tag
- tag.description Description of the tag @tag.description cool description|
- tag.docs.url The URL of the external documentation for the tag @tag.docs.url https://example.com
- etc.
[Strongly look at the official annotation rules]( swag/README.md at master swaggo/swag (github.com) )