11

【笔记】Go将Gin整合Swagger自动生成API文档

 2 years ago
source link: https://loli.fj.cn/2023/04/18/Go%E5%B0%86Gin%E6%95%B4%E5%90%88Swagger%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90API%E6%96%87%E6%A1%A3/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go将Gin整合Swagger自动生成API文档学习笔记

下载可执行文件

go install github.com/swaggo/swag/cmd/[email protected]

在项目中下载依赖

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

在Gin的路由中添加Swagger的路由

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

func main() {
app := gin.Default()

app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

app.Run()
}

在函数前添加Swagger语法的注释

  • 在主函数上添加全局API文档注释
  • 在接口函数上添加接口API文档注释

_ "demo/docs":指定swag init生成的文档目录的相对路径作为包引入

在主函数上添加全局API文档注释

@title:标题
@version:版本号
@description:文档描述
@contact.name:作者名
@contact.email:作者邮箱
@host:访问地址
@basePath:项目访问路径

在接口函数上添加接口API文档注释

@tag:标签
@summary:接口标题
@description:接口描述
@param:接口参数

第1个参数:参数变量名
第2个参数

query:请求头携带的参数
body:请求体携带的参数

第3个参数:数据类型
第4个参数:是否是必须,true必须,false不必须
第5个参数:参数描述

@router /index [get]:路由

第1个参数:请求URL
第2个参数:请求类型

@produce:请求数据格式
@success 200 :成功处理的响应

demo/main.go

import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "demo/docs"
)

type Request struct {
Key string `json:"key"`
}

type Response struct {
Code string `json:"code"`
Msg string `json:"data"`
}

// @title xxx
// @version v1.0
// @description xxx
// @contact.name xxx
// @contact.email [email protected]
// @host 127.0.0.1:8080
// @basePath /
func main() {
app := gin.Default()

app.GET("/index", Index)
app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

app.Run()
}

// Index 首页
// @tag xxx模块
// @summary xxx功能
// @description xxx
// @param xxx query Request false "xxx"
// @param xxx body string true "xxx"
// @router /index [get]
// @produce json
// @success 200 {object} Response
func Index(context *gin.Context) {
context.JSON(200, Response{0, "ok"})
}
  • 每次改动Swagger语法的注释后都需要重新生成文档
swag init
  • 会在当前位置自动创建docs目录,并存放生成后的文档

哔哩哔哩——枫枫知道


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK