1.安装 swagger插件
1
| go install github.com/swaggo/swag/cmd/swag@latest |
2.将通用API注释写在main.go中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package main
import (
"docs"
swaggerFiles "github.com/swaggo/files" // swagger embed files
ginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware
)
// @title Chop a Sabre API
// @version 1.0
// @description Interface document of Chop a Sabre.
// @termsOfService http://swagger.io/terms/
// @contact.name To be named
// @contact.url Undetermined
// @contact.email Undetermined
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
func main() {
r := gin.Default()
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
c := controller.NewController()
v1 := r.Group("/api/v1")
{
user:= v1.Group("/User")
{
user.POST("", c.AddAccount)
user.DELETE(":id", c.DeleteAccount)
}
}
r.Run(":8080")
} |
3.在Api接口函数上方写上注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| // RegisterAccount godoc
// @Summary Register an account
// @Description get string by ID
// @Tags Register User
// @Accept json
// @Produce json
// @Param username formData string true "用户名"
// @Param password formData string true "用户密码"
// @Success 200 {object} FormRegister
// @Failure 400 {string} json "{"err": err.Error()}"
// @Router /api/v1/register/{username}/{password} [post]
func (l *Login) Register(c *gin.Context) {
var formRegister FormRegister
err := utils.Bind(c, &formRegister)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err: ": err.Error()})
return
}
c.JSON(http.StatusOK, formRegister)
return
} |
4.初始化swagger配置