gin集成swagger自動(dòng)生成接口文檔

環(huán)境配置

1、 向您的 API 源代碼添加注釋,請(qǐng)參閱聲明性注釋格式
2、使用以下命令下載Swag for Go:
3、下載依賴包

go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files

代碼中進(jìn)行配置

1、router.go中配置
import (
   "github.com/swaggo/files"
   "github.com/swaggo/gin-swagger"
   _ "xxxx/docs"
   "github.com/gin-gonic/gin"
)

// 設(shè)置swagger路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

2、main.go中配置添加注釋:

// @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

// @in header

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// 下面注釋按照項(xiàng)目實(shí)際的地址和路徑進(jìn)行設(shè)置
// @host 127.0.0.1:8093 
// @BasePath /api/manage

func main() {
   // 接收參數(shù)
   flag.StringVar(&mode, "mode", "server", "運(yùn)行模式,運(yùn)行server服務(wù)或者執(zhí)行migrate.")
   flag.StringVar(&confPath, "c", "./configs/config.yaml", "配置文件路徑.")
   flag.Parse()

   // 參數(shù)合法性校驗(yàn)
   if mode != "server" && mode != "migrate" {
      log.Fatal("run 參數(shù)非法: 運(yùn)行模式只能選擇 server 或 migrate")
   }

   // 初始化
   Setup()

   // 根據(jù)參數(shù)執(zhí)行對(duì)應(yīng)模式服務(wù)
   if mode == "server" {
      runServer()
   } else {
      migrate.MigrateTable()
   }
}

3、在具體的請(qǐng)求方法中添加注釋

// List
// @通知信息列表
// @Description List
// @Accept  json
// @Produce json
// @Param   offset     path    int     true        "15"
// @Param   limit     path    int     true        "15"
// @in header
// @Success 200 {string} string    "ok"
// @Router /notice [get]
func List(c *gin.Context) {
   // 分頁(yè)參數(shù)
   offset, limit, err := request.GetPagerParams(c)
   if err != nil {
      response.ParamsError(c, err.Error())
      return
   }
   // 排序條件
   orderExpr, err := request.GetOrderParams(c)
   if err != nil {
      response.ParamsError(c, err.Error())
      return
   }

   // 查詢db獲取數(shù)據(jù)
   results := make([]*notice.Notice, 0)
   count, err := model.GetPageListWithSearch(&results, offset, limit, orderExpr, c.Query("search"), nil)

   if err != nil {
      response.BaseError(c, err.Error())
      return
   }

   respData := &RespList{
      List:  make([]*RespItem, len(results)),
      Count: count,
   }
   // 組裝返回類型
   for ix, item := range results {
      d := &RespItem{
         ID:        item.ID,
         Source:    item.Source,
         Type:      item.Type,
         Contacts:  item.Contacts,
         Content:   item.Content,
         Result:    item.Result,
         CreatedAt: item.CreatedAt.Format("2006-01-02 15:04:05"),
         UpdatedAt: item.UpdatedAt.Format("2006-01-02 15:04:05"),
      }
      respData.List[ix] = d
   }
   // 返回請(qǐng)求
   response.Success(c, respData)
}

4、執(zhí)行初始化命令

swag init // 注意,一定要和main.go處于同一級(jí)目錄

初始化命令,在根目錄生成一個(gè)docs文件夾,每次注釋變更,都需要執(zhí)行此步驟,開始沒(méi)有找到swag命令,命令位置在$GOPATH/bin/swag

5、訪問(wèn)接口文檔

地址為:http://127.0.0.1:8093/swagger/index.html
接口文檔樣例:

image.png

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

推薦閱讀更多精彩內(nèi)容