前置準備
安裝
# 安裝
go get "github.com/swaggo/files"
go get "github.com/swaggo/gin-swagger"
go install github.com/swaggo/swag/cmd/swag@latest
給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改好後重新安裝
go install github.com/swaggo/swag/cmd/swag@latest
[問題及其處理] swagger Failed to load API definition
因為import的時候少了:_ "項目名稱/docs"
import (
_ "項目名稱/docs"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
添加註釋
項目註釋
在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)))
參考資料
官方issue:https://github.com/swaggo/gin-swagger/issues/90