go swag 工具的使用

安装

go install github.com/swaggo/swag/cmd/swag@latest

编写注释文档

编写通用API注释:

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

// @contact.name   API Support
// @contact.url    http://www.swagger.io/support
// @contact.email  support@swagger.io

// @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

// @externalDocs.description  OpenAPI
// @externalDocs.url          https://swagger.io/resources/open-api/

添加API操作注释:

// ShowAccount godoc
// @Summary      Show an account
// @Description  get string by ID
// @Tags         accounts
// @Accept       json
// @Produce      json
// @Param        id   path      int  true  "Account ID"
// @Success      200  {object}  model.Account
// @Failure      400  {object}  httputil.HTTPError
// @Failure      404  {object}  httputil.HTTPError
// @Failure      500  {object}  httputil.HTTPError
// @Router       /accounts/{id} [get]

生成 openapi 文档

# http/controller 为API接口所在的文件夹
swag fmt -d http/controller
# http/api.go 为通用API注释所在的文件
swag init -g http/api.go

引入依赖

import (
	_ "<your_go_module>/docs"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func routers() *gin.Engine {
	r := gin.Default()
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	return r
}

最后访问文档地址:http://localhost:8080/swagger/index.html

formData 接口注释写法

type UploadFileReq struct {
	Filename string                `form:"filename" binding:"required"`
	File     *multipart.FileHeader `form:"file" binding:"required" swaggertype:"string" format:"binary"`
}
// UploadFile godoc
//
//	@Summary		上传文件
//	@Description	上传文件
//	@Tags			Example
//	@Accept			mpfd
//	@Produce		json
//	@Param			payload	formData	UploadFileReq	true	"请求参数"
//	@Success		200		{object}	any
//	@Router			/upload_file [post]
posted @ 2025-02-19 11:43  nptr  阅读(39)  评论(0)    收藏  举报