Go語(yǔ)言Swagger實(shí)現(xiàn)為項(xiàng)目生成 API 文檔
安裝 Swagger
全局安裝 swag CLI
swag 是 Swagger 的命令行工具,用于生成 API 文檔。可以通過(guò)以下命令全局安裝:
go get github.com/swaggo/swag/cmd/swag@latest go install github.com/swaggo/swag/cmd/swag@latest
項(xiàng)目依賴(lài)安裝
在項(xiàng)目中需要安裝以下依賴(lài)以支持 Gin 和 Swagger 的集成:
go get github.com/swaggo/gin-swagger go get github.com/swaggo/files go get github.com/alecthomas/template
格式化 Swagger 注釋
使用 swag fmt 命令可以格式化項(xiàng)目中的 Swagger 注釋?zhuān)_保注釋符合規(guī)范:
swag fmt
使用 swag CLI 生成文檔
運(yùn)行以下命令生成 Swagger 文檔(默認(rèn)生成 docs.go、swagger.json 和 swagger.yaml 文件):
swag init
swag init 常用選項(xiàng)
| 選項(xiàng) | 說(shuō)明 | 默認(rèn)值 |
|---|---|---|
| --generalInfo, -g | 指定包含通用 API 信息的 Go 文件路徑 | main.go |
| --dir, -d | 指定解析的目錄 | ./ |
| --exclude | 排除解析的目錄(多個(gè)目錄用逗號(hào)分隔) | 空 |
| --propertyStrategy, -p | 結(jié)構(gòu)體字段命名規(guī)則(snakecase、camelcase、pascalcase) | camelcase |
| --output, -o | 輸出文件目錄(swagger.json、swagger.yaml 和 docs.go) | ./docs |
| --parseVendor | 是否解析 vendor 目錄中的 Go 文件 | 否 |
| --parseDependency | 是否解析依賴(lài)目錄中的 Go 文件 | 否 |
| --parseInternal | 是否解析 internal 包中的 Go 文件 | 否 |
| --instanceName | 設(shè)置文檔實(shí)例名稱(chēng) | swagger |
示例:
swag init --dir ./ --output ./docs --propertyStrategy snakecase
Swagger 注釋格式
Swagger 使用聲明式注釋來(lái)定義 API 的元信息。以下是常用注釋及其說(shuō)明:
通用 API 信息
通常在 main.go 中定義,用于描述整個(gè) API 的基本信息:
// @title Swagger Example API // @version 1.0 // @description This is a sample server celler 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:8080 // @BasePath /api/v1 // @schemes http https
API 路由注釋
在具體路由處理函數(shù)上方添加注釋?zhuān)x該接口的行為:
// GetPostById
// @Summary 獲取文章信息
// @Produce json
// @Param id path string true "文章ID"
// @Success 200 {object} Post "成功返回文章信息"
// @Failure 400 {string} string "請(qǐng)求參數(shù)錯(cuò)誤"
// @Router /post/{id} [get]
func GetPostById(c *gin.Context) {
// 函數(shù)實(shí)現(xiàn)
}
@Summary:接口簡(jiǎn)述@Produce:返回的 MIME 類(lèi)型@Param:參數(shù)定義(格式:名稱(chēng) 位置 類(lèi)型 是否必填 描述)@Success:成功響應(yīng)(格式:狀態(tài)碼 {類(lèi)型} 數(shù)據(jù)結(jié)構(gòu) 描述)@Failure:失敗響應(yīng)@Router:路由路徑和方法
示例項(xiàng)目代碼
以下是一個(gè)完整的示例,展示如何在 Gin 項(xiàng)目中集成 Swagger:
package main
import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"strconv"
_ "swagger/docs" // 導(dǎo)入生成的 Swagger 文檔
)
// Post 文章結(jié)構(gòu)體
type Post struct {
ID int64 `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Description string `json:"description"`
}
func main() {
r := gin.Default()
r.GET("/post/:id", GetPostById)
// 配置 Swagger 路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
// GetPostById 獲取文章信息
// @Summary 獲取文章信息
// @Produce json
// @Param id path string true "文章ID"
// @Success 200 {object} Post "成功返回文章信息"
// @Failure 400 {string} string "請(qǐng)求參數(shù)錯(cuò)誤"
// @Router /post/{id} [get]
func GetPostById(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.String(400, err.Error())
return
}
c.JSON(200, Post{
ID: id,
Title: "codepzj",
Content: "測(cè)試",
Description: "測(cè)試",
})
}
生成并訪(fǎng)問(wèn)文檔
運(yùn)行 swag init 生成文檔。
啟動(dòng)項(xiàng)目:go run main.go。
在瀏覽器中訪(fǎng)問(wèn) http://localhost:8080/swagger/index.html,即可查看交互式 API 文檔。

總結(jié)
通過(guò) swag 和 gin-swagger,我們可以輕松為 Go 項(xiàng)目生成規(guī)范的 API 文檔。只需要編寫(xiě)簡(jiǎn)單的注釋?zhuān)琒wagger 就能自動(dòng)生成交互式的文檔頁(yè)面,方便開(kāi)發(fā)和調(diào)試。
到此這篇關(guān)于Go語(yǔ)言Swagger實(shí)現(xiàn)為項(xiàng)目生成 API 文檔的文章就介紹到這了,更多相關(guān)Go Swagger生成API內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang執(zhí)行命令獲取執(zhí)行結(jié)果狀態(tài)(推薦)
這篇文章主要介紹了golang執(zhí)行命令獲取執(zhí)行結(jié)果狀態(tài)的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-11-11
Golang 錯(cuò)誤捕獲Panic與Recover的使用
對(duì)于Go語(yǔ)言的錯(cuò)誤是通過(guò)返回值的方式,本文主要介紹了Golang 錯(cuò)誤捕獲Panic與Recover的使用,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

