安装swag
go get -u github.com/swaggo/swag/cmd/swag
配置代码
package mainimport (_ "code/docs""github.com/gin-gonic/gin"ginSwagger "github.com/swaggo/gin-swagger""github.com/swaggo/gin-swagger/swaggerFiles")// @title Swagger Example API(文档标题)// @version 1.0 (版本)// @description This is a sample server celler server.(描述,可不写)// @termsOfService https://razeen.me ()// @contact.name Razeen// @contact.url https://razeen.me// @contact.email me@razeen.me// @license.name Apache 2.0// @license.url http://www.apache.org/licenses/LICENSE-2.0.html// @host 127.0.0.1:8080// @BasePath /api/v1func main() {r := gin.Default()r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))// 其他接口// ...r.Run(":8080")}
:::danger
注意: 在程序运行前,需要引入 doc(使用swag init生成).例如代码中的 import _ “code/docs”, 只需要在main.go中引入
:::

注释说明:
// @title Swagger Example API(文档标题)
// @version 1.0 (版本)
// @description This is a sample server celler server.(描述,可不写)
// @host 127.0.0.1:8080 (用于在线执行WEBAPI请求,需要正确填写)
// @BasePath /api/v1 (用于在线执行WEBAPI请求,需要正确填写)
// @termsOfService https://razeen.me (可不写)
// @contact.name Razeen (可不写)
// @contact.url https://razeen.me (可不写)
// @contact.email me@razeen.me (可不写)
// @license.name Apache 2.0 (可不写)
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html (可不写)
添加注释信息
// @Summary 测试SayHello// @Description 向你说Hello// @Tags 测试// @Accept json// @Produce json// @Param who query string true "人名" Enums(lz, xiao, ming) default(lz)// @Param body body Pet true "参数信息说明"// @Success 200 {string} string "{"msg": "hello Razeen"}"// @Failure 400 {object} APIError "{"code": 400, "msg": "who are you"}"// @Router /hello [get]func Hello(c *gin.Context) {who := c.Query("who")if who == "" {c.JSON(http.StatusBadRequest, gin.H{"msg": "who are u?"})return}c.JSON(http.StatusOK, gin.H{"msg": "hello " + who})}
Tags
Accept
接收的参数类型,支持表单(mpfd) , JSON(json)等,更多如下表。
Produce
返回的数据结构,一般都是json, 其他支持如下表:
| Mime Type | 声明 |
|---|---|
| application/json | json |
| text/xml | xml |
| text/plain | plain |
| html | html |
| multipart/form-data | mpfd |
| application/x-www-form-urlencoded | x-www-form-urlencoded |
| application/vnd.api+json | json-api |
| application/x-json-stream | json-stream |
| application/octet-stream | octet-stream |
| image/png | png |
| image/jpeg | jpeg |
| image/gif | gif |
Param
参数,从前往后分别是:
@Param who query string true “人名”
@Param 1.参数名 2.参数类型 3.参数数据类型 4.是否必须 5.参数描述 6.其他属性
参数名
参数名就是我们解释参数的名字。
参数类型
参数类型主要有四种:
path 该类型参数直接拼接在URL中,如Demo中HandleGetFile:
// @Param id path integer true “文件ID”
query 该类型参数一般是组合在URL中的,如Demo中HandleHello
// @Param who query string true “人名”
formData 该类型参数一般是POST,PUT方法所用,如Demo中HandleLogin
// @Param user formData string true “用户名” default(admin)
body 当Accept是JSON格式时,我们使用该字段指定接收的JSON类型
// @Param param body main.JSONParams true “需要上传的JSON”
参数数据类型
主要支持一下几种:注意,如果你是上传文件可以使用file, 但参数类型一定是formData, 如下:
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
是否可选
是否是必须表明该参数是否是必须需要的,必须的在文档中会黑体标出,测试时必须填写。
参数描述
参数的一些说明
其他属性
除了上面这些属性外,我们还可以为该参数填写一些额外的属性,如枚举,默认值,值范围等。
枚举// @Param enumstring query string false "string enums" Enums(A, B, C)// @Param enumint query int false "int enums" Enums(1, 2, 3)// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)值添加范围// @Param string query string false "string valid" minlength(5) maxlength(10)// @Param int query int false "int valid" mininum(1) maxinum(10)设置默认值// @Param default query string false "string default" default(A)组合使用// @Param enumstring query string false "string enums" Enums(A, B, C) default(A)
Success
指定成功响应的数据。格式为:
// @Success 1.HTTP响应码 {2.响应参数类型} 3.响应数据类型 4.其他描述
HTTP响应码
例如: 200,400,500
响应参数类型 / 响应数据类型
返回的数据类型,可以是自定义类型,可以是json。
返回一些指定的模型序列化JSON的数据:
// @Success 200 {object} main.File
返回模型数组:
// @Success 200 {anrry} main.File
string:
// @Success 200 {string} string “”
Failure
Router
指定路由与HTTP方法。格式为:
// @Router /path/to/handle [HTTP方法]
当使用路径时:
// @Param id path string true "id"...// @Router /scheduler/{id} [delete]
运行并查看
- 项目目录下运行: swag init (若main.go不在根目录,应该使用 swag -g cmd/main.go 指定文件位置)
- 运行程序
- 访问http://127.0.0.1:8080/swagger/index.htm
:::warning 注意: 当程序或注释修改之后需要先执行 swag init , 在运行程序,顺序不能反 :::
格式化
swaggo 提供了 swag fmt 工具,可以针对Swag的注释自动格式化,就像go fmt,让注释看起来更统一。
示例:
swag fmt
排除目录(不扫描)示例:
swag fmt -d ./ —exclude ./internal
指定 main.go 文件示例:
swag fmt -g cmd/api/api.go
常见问题
main.go不在根目录下
若直接使用swag init, 生成的swag init的文档是空的. 可以使用 -g参数指定目录即可正常显示
swag init -g cmd/main.go
any类型参数不能明确显示
type Response struct {Code intMsg stringData any}
其中Data字段不能现在swagger中显示实际存放的类型. 可以在swagger的注释中按照如下方式写:
// @Success 200 {object} service.Response{data=models.Schedule}
外部包不能正确解析
import "github.com/jinzhu/gorm"type Schedule struct {gorm.ModelMessage string}// @Param body body models.Schedule true "计划内容"
Schedule中使用外部包gorm,在swagger中不能正常解析, 可以使用如下参数,解析额外参数:
swag init —parseDependency —parseInternal
https://github.com/swaggo/swag/issues/810#issuecomment-728643872
参考资料
Go语言之使用 swaggo 一键生成 API 文档
https://github.com/swaggo/gin-swagger
官方文档(英文)
[详细]使用swaggo自动生成Restful API文档
在线修改swagger.json
