前置准备
安装
# 安装
go get "github.com/swaggo/files"
go get "github.com/swaggo/gin-swagger"
给swagger配置路由
import
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "你的项目名称/docs"
r := gin.Default()
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
例行公事
概要
后续swagger就是例行公事:
- 添加(修改)注释
- 生成配置文件,运行swag init
- 重启服务
- 查看结果http://localhost:你的端口/swagger/index.html
swag init报错找不到命令
如果没有出现这个错误可以直接跳到下面,定位:
- 第一反应是gopath没配置环境变量,但之前的都能用,就这个不太行,找到gopath/bin下发现没有这个,尝试重新安装,没有报错也无法执行
之前为了部署go项目,把环境改成了Linux,把环境改回windows
go env -w GOOS=windows go env -w CGO_ENABLED=1
改好后重新安装
添加注释
项目注释
在main.go里添加注释(下面的url描述等都可以修改)
// @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 localhost:你的端口号
// @BasePath /
添加接口注释
如下是get请求,传递一个参数id,有什么接口要写参数,复制黏贴改改,或者让ai帮你写好
// @Summary 根据id获取页面信息
// @Description Get a single page by ID
// @Tags pages
// @Accept json
// @Produce json
// @Param id query int true "页面id"
// @Success 200 {object} model.Page
// @Failure 400 {string} string "Invalid ID supplied"
// @Failure 404 {string} string "Page not found"
// @Router /cc/page/ [get]
func (p PageObject) GetById(c *gin.Context) {
// 业务代码
}
model参数
// @Description Page represents the PAGES table
type Page struct {
// ID represents the auto-increment primary key
// @Description 自增ID,主键
// @Example 1
ID int64 `gorm:"column:ID;primary_key;AUTO_INCREMENT;NOT NULL;comment:'自增ID,主键'" json:"ID"`
}
进阶
如何添加用户认证
修改
main中添加如下:
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
我的理解是整个ApiKeyAuth的名称是什么无所谓,只要使用的时候保持一致就行
注册路由,从第一句改为下一句
// r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.PersistAuthorization(true)))
需要认证的接口,添加注释
// @Security ApiKeyAuth
重新运行swag init,重启后端服务
使用
点下右上角,添加header内容
try it out时,会自动添加上header
跨域问题
添加如下代码,特别是测试环境可能需要跨域操作,如果想正式和测试不同,可以把下面代码抽象成配置文件
import (
"github.com/gin-contrib/cors"
)
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"}, // 或者指定允许的域名,例:"http://example.com"
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
// r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.PersistAuthorization(true)))
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。