GO 的 Web 开发系列(五)—— 使用 Swagger 生成一份好看的接口文档

经过前面的文章,已经完成了 Web 系统基础功能的搭建,也实现了 API 接口、HTML 模板渲染等功能。接下来要做的就是使用 Swagger 工具,为这些 Api 接口生成一份好看的接口文档。

一、写注释

注释是 Swagger 的灵魂,Swagger 是通过特定格式的注释生成接口文档的。

1.1 基础注释

这部分基础注释对全接口文档通用,指定接口文档的基础信息,可添加在 main 函数上。

注释说明示例
title必填 应用程序的名称。// @title Swagger Example API
version必填 提供应用程序API的版本。// @version 1.0
description应用程序的简短描述。// @description This is a sample server celler server.
tag.name标签的名称。// @tag.name This is the name of the tag
tag.description标签的描述。// @tag.description Cool Description
tag.docs.url标签的外部文档的URL。// @tag.docs.urlhttps://example.com
tag.docs.description标签的外部文档说明。// @tag.docs.description Best example documentation
termsOfServiceAPI的服务条款。// @termsOfServicehttp://swagger.io/terms/
contact.name公开的API的联系信息。// @contact.name API Support
contact.url联系信息的URL。 必须采用网址格式。// @contact.urlhttp://www.swagger.io/support
contact.email联系人/组织的电子邮件地址。 必须采用电子邮件地址的格式。// @contact.emailsupport@swagger.io
license.name必填 用于API的许可证名称。// @license.name Apache 2.0
license.url用于API的许可证的URL。 必须采用网址格式。// @license.urlhttp://www.apache.org/licenses/LICENSE-2.0.html
host运行API的主机(主机名或IP地址)。// @host localhost:8080
BasePath运行API的基本路径。// @BasePath /api/v1
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。// @accept json
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。// @produce json
query.collection.format请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv。// @query.collection.format multi
schemes用空格分隔的请求的传输协议。// @schemes http https
externalDocs.descriptionDescription of the external document.// @externalDocs.description OpenAPI
externalDocs.urlURL of the external document.// @externalDocs.urlhttps://swagger.io/resources/open-api/
x-name扩展的键必须以x-开头,并且只能使用json值// @x-example-key {“key”: “value”}

1.2 API 接口注释

这部分注释用于声明一个接口,可将这部分注释添加到相应的接口方法上。

注释描述
description操作行为的详细说明。
description.markdown应用程序的简短描述。该描述将从名为endpointname.md的文件中读取。
id用于标识操作的唯一字符串。在所有API操作中必须唯一。
tags每个API操作的标签列表,以逗号分隔。
summary该操作的简短摘要。
acceptAPI 可以使用的 MIME 类型列表。 请注意,Accept 仅影响具有请求正文的操作,例如 POST、PUT 和 PATCH。 值必须如“Mime类型”中所述。
produceAPI可以生成的MIME类型的列表。值必须如“Mime类型”中所述。
param用空格分隔的参数。param name,param type,data type,is mandatory?,comment attribute(optional)
security每个API操作的安全性。
success以空格分隔的成功响应。return code,{param type},data type,comment
failure以空格分隔的故障响应。return code,{param type},data type,comment
response与success、failure作用相同
header以空格分隔的头字段。return code,{param type},data type,comment
router以空格分隔的路径定义。path,[httpMethod]
deprecatedrouter与router相同,但是是deprecated的。
x-name扩展字段必须以x-开头,并且只能使用json值。
deprecated将当前API操作的所有路径设置为deprecated

1.3 类型枚举

以上接口注解中用到的枚举类型的介绍。

Mime 类型枚举:

swag 接受所有格式正确的 MIME 类型, 即使匹配 */*。除此之外,swag 还接受某些 MIME 类型的别名。

AliasMIME Type
jsonapplication/json
xmltext/xml
plaintext/plain
htmltext/html
mpfdmultipart/form-data
x-www-form-urlencodedapplication/x-www-form-urlencoded
json-apiapplication/vnd.api+json
json-streamapplication/x-json-stream
octet-streamapplication/octet-stream
pngimage/png
jpegimage/jpeg
gifimage/gif

参数类型枚举:

参数类型描述
query请求的 url 参数
path放在请求路径中的参数
header请求 header 中的参数
body请求 body 中的参数
formDatax-www-form-urlencoded 请求是的表单参数

数据类型枚举:

数据类型对应实际类型
stringstring
integerint, uint, uint32, uint64
numberfloat32
booleanbool
结构体结构体类型

更多用法内容可参考官方文档:https://github.com/swaggo/swag/blob/master/README_zh-CN.md

1.4 示例

通用 API 示例:

以下注释指定了文档的基本信息,以及基于 apikey 方式的一种安全校验方式:

// @title Aurora Admin-API 文档
// @version v0.0.1
// @description Aurora 建站
// @contact.name nineya
// @contact.url https://www.nineya.com
// @contact.email 361654768@qq.com
// @schemes http https
// @host localhost:8888
// @BasePath /api/admin
// @produce json
// @securityDefinitions.apikey admin
// @in header
// @name Admin-Authorization

注解不能放在 @securityDefinitions 相关注解的后面,否则将不会被解析

接口 API 示例:

// @summary Upload attachment by id
// @description Upload attachment by id
// @tags attachment
// @accept json
// @produce json
// @param id path id true "Attachment id"
// @param param body request.UpdateAttachmentParam true "Attachment name and team information"
// @success 200 {object} response.Response
// @security admin
// @router /attachment/{id} [put]

二、文档生成

使用命令下载 swag:

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

使用命令生成 swag 所需的文件:

swag init

这将会扫描源程序,解析注释并生成 docs 文件夹和文档信息文件。

三、与 Gin 集成

下载安装 gin-swagger :

go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files

导入 docs下的文件:

import (
   _ "go-project-name/docs"
)

添加 Gin 路由:

swaggerGroup := router.Group("swagger")
swaggerGroup.GET("/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

通过 /swagger/index.html 可以访问到文档:

四、多文档

我们一个系统可能包含开发者、用户、管理员多种角色,我们需要为不同的角色分别创建接口文档。

4.1 生成文档

要生成多份文档,在生成文档时就不能直接执行 swag init 命令了,需要指定更多的参数:

swag init -h
NAME:
   swag init - Create docs.go
USAGE:
   swag init [command options] [arguments...]
OPTIONS:
   --generalInfo value, -g value          API通用信息所在的go源文件路径,如果是相对路径则基于API解析目录 (默认: "main.go")
   --dir value, -d value                  API解析目录 (默认: "./"),多个目录可用逗号分隔
   --exclude value                        解析扫描时排除的目录,多个目录可用逗号分隔(默认:空)
   --propertyStrategy value, -p value     结构体字段命名规则,三种:snakecase,camelcase,pascalcase (默认: "camelcase")
   --output value, -o value               文件(swagger.json, swagger.yaml and doc.go)输出目录 (默认: "./docs")
   --parseVendor                          是否解析vendor目录里的go源文件,默认不
   --parseDependency                      是否解析依赖目录中的go源文件,默认不
   --markdownFiles value, --md value      指定API的描述信息所使用的markdown文件所在的目录
   --generatedTime                        是否输出时间到输出文件docs.go的顶部,默认是
   --codeExampleFiles value, --cef value  解析包含用于 x-codeSamples 扩展的代码示例文件的文件夹,默认禁用
   --parseInternal                        解析 internal 包中的go文件,默认禁用
   --parseDepth value                     依赖解析深度 (默认: 100)
   --instanceName value                   设置文档实例名 (默认: "swagger")

可分别为每份文档执行以下命令方法生成多份文档:

swag init -g 通用API所在Go文件 -d  API解析目录 --exclude 排除的目录 -o 文档输出目录 --instanceName 文档实例名

举例小玖的结构体对象所在目录为 internal/application/param,Admin 接口所在目录为internal/application/router/api/admin,Content 接口所在目录为 internal/application/router/api/content。

Admin 文档命令:

swag init -g index.go -d internal/application/router/api/admin,internal/application/param -o ./docs/admin --instanceName=admin

Content 文档命令:

swag init -g index.go -d internal/application/router/api/content,internal/application/param -o ./docs/content --instanceName=content

注意:

-g 参数的路径相对于 -d 参数的第一个路径。

如果 -d 指定的路径下没有 Go 文件,会有 execute go list command, exit status 1, stdout:, stderr:no Go files in ... 错误提示,无影响。

4.2 与 Gin 集成

导入 docs 下的文件:

import (
   _ "go-project-name/docs/admin"
   _ "go-project-name/docs/content"
)

添加 Gin 路由:

swaggerGroup := router.Group("swagger")
swaggerGroup.GET("/admin/*any", ginSwagger.WrapHandler(
  swaggerFiles.NewHandler(), func(config *ginSwagger.Config) { config.InstanceName = "admin"
  }))
swaggerGroup.GET("/content/*any", ginSwagger.WrapHandler(
  swaggerFiles.NewHandler(), func(config *ginSwagger.Config) { config.InstanceName = "content"
  }))

通过 /swagger/admin/index.html 和 /swagger/content/index.html 可以分别访问到两份文档。