第一步:main函数入口处增加注释
import (
"github.com/gin-gonic/gin"
_"demo/docs" // 一定要导入自己项目的docs目录,否则会报错 not yet registered swag
gs "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
// 版本可能会有变化
swaggerFiles "github.com/swaggo/files"
)
// 查看完整swagger api注释文档
// @title DEMO服务
// @version 1.0
// @description 对服务的一个大概描述
// @termsOfService http://swagger.io/terms/
// @contact.name
// @contact.url http://www.swagger.io/support
// @contact.email l23@qq.com(开发邮箱)
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host 127.0.0.1:88 调用的IP端口
// @BasePath / 前缀通用路径
func main() {
router := gin.Default()
router.GET("/swagger/*any",gs.WrapHandler(swaggerFiles.Handler))
router.Run(":80")
}
第二步:安装swagger
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/files
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles
项目执行以下命令,会在项目下生成docs目录,会有三个文件docs.go swagger.json swagger.yaml
# 注意执行此命令的是时候,保持在main.go所在目录,否则找不到入口
swag init
第三步:访问文档
启动项目,访问http://127.0.0.1:88/swagger/index.html既可看到如下图:
第四步:接口上添加注释
// @Title 用户相关
// @Summary 注册接口
// @Description
// @Tags 用户注册接口
// @Accept application/json
// @Produce application/json
// @Param object body request.Register true "body参数"
// @Security ApiKeyAuth
// @Success 200 {object} {"code":200,"data":null,"msg":""}
// @Failure 400 {string} {"code":100,"data":null,"msg":""}
// @Router /base/register [post]
经常用的注释 括号为解释 (参数名 数据传输方式 类型 是否必填 comment )
// 表单参数
// @Param username formData string true "用户名"
// url查询参数
// @Param qqq query string true "用户名" ( 查询参数 ?qqq=1)
// url path参数
// @Param www path string true "www" (url参数 /{www}/test)
// header头参数
// @Param Authorization header string true "Bearer 111111111"
// @Param Cookies header string true "token=111111111"
// @Param AccessKey header string true "accesskey"
// @Param Authorization header string true "Bearer 111111111"
func Register(c *gin.Context) {
}
添加之后,执行swag init,注释更新之后,记得执行命令,否则不生效。可以直接点击swagger来测试接口!!!
更多注释,请查看文档
大家有更多注释,欢迎在评论区留言
版本注意:go 版本 go1.20.3 windows/amd64中需要替换安装指令
安装swag
go install github.com/swaggo/swag/cmd/swag@latest
报错如下:
解决方案: