Skip to content

GinSwagTutorials

餘生很長 別慌張 edited this page Jan 11, 2019 · 10 revisions

swagger API文档教程

在编写完 http api 接口后,为了让客户端开发者能够清晰明白相关接口的调用方式及规则,我们需要写一个专门的接口说明文档,编写这类文档,方式有很多,比如使用 word、markdown 等,甚至还可以使用 postman 导出文件,但这些有一定局限且始终感觉不够专业,于是这里来讲swagger,一种时下较为主流的文档工具;

swagger 在 go 中我找到了两种方案:

个人偏向使用:gin-swagger,它仅需要在接口处添加相关关键字语法注释即可生成对应接口文档, 而go-swagger看后发现它有一套独立的开发流程, 首先需要编写yaml格式的接口配置文件, 然后使用命令将yaml格式文件作为输入生成一套代码框架, 最后需要对框架进行业务逻辑填充, 当然它也提供了通过语法注释的方式生成文档,但感觉没有gin-swagger简单明了,个人喜好最终选择gin-swagger

文档生成步骤

1. 向API源代码接口方法添加注释

swaggo提供了一套用于定义API的声明注释格式,文档可以查阅:Declarative Comments Format 这里swagger文档的基本信息应该定义在main文件中:

// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore 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 petstore.swagger.io
// @BasePath /v2
func main() { 
    ...
}

swagger接口的定义大致如下:

// @Summary 账号注册
// @Description 通过邮箱密码注册账号
// @Accept json
// @Produce json
// @Tags auth
// @ID auth.signup
// @Param body body v1.SignupRequest true "账号注册请求参数"
// @Success 200 {string} json "{"status":200, "code": 2000001, msg:"请求处理成功"}"
// @Failure 400 {string} json "{"status":400, "code": 4000001, msg:"请求参数有误"}"
// @Failure 500 {string} json "{"status":500, "code": 5000001, msg:"服务器内部错误"}"
// @Router /auth/signup [post]
func (ac AuthController) Signup(c *gin.Context) {...}

在定义接口传参数据结构时,可参照swaggo attribute的属性说明;

代码中的定义可参考控制器层controller/v1下 swagger 注释内容;

2. 下载安装swag命令行工具
$ go get -u github.com/swaggo/swag/cmd/swag

注意:若go get无法下载,可以尝试使用gopm进行下载;

3. 生成swagger文档

需要在main.go所在的项目根路径下执行文档生成命令,在此之前文档注释内容应已添加完成:

swag init

命令执行完后,会在当前目录下生成docs/目录,且该目录下有doc.go文件

4. 导入相关依赖并设置访问路由
package main
import (
	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	_ "./docs" // 这里需要将生成的文档导入进来
)

// swagger docs ...
func main() {
    r := gin.New()
    // 设置 swagger 文档访问路由并使用 ginSwagger 中间件 
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run()
}

注:下载会在go mod模式下执行go build时对相关缺失包进行统一下载安装;

5. 访问 swagger 文档

使用 http://localhost:8000/swagger/index.html 来访问你所创建的文档内容;

Howl, caught in the open

Down, it's bleak and it's sobering

Flower, bloom in the broken

Cower, doped to recovering

Clone this wiki locally