天天看點

Gloang Swagger——自動生産接口文檔

功能

自動生産接口文檔

安裝

# 安裝swag
go get -u github.com/swaggo/swag/cmd/swag
# 安裝 gin-swagger
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles      

編寫API注釋

例1-新增

// @Summary 新增文章标簽
// @Produce  json
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param created_by query string false "CreatedBy"
// @Success 200 {object} app.Response
// @Success 500 {object} app.Response
// @Router /api/tags [post]
func AddTag(c *gin.Context) {
...
}      

例2-編輯

// @Summary 編輯文章标簽
// @Produce  json
// @Param id path int true "ID"
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param modified_by query string false "ModifiedBy"
// @Success 200 {object} app.Response
// @Success 500 {object} app.Response
// @Router /api/tags/{id} [put]
func EditTag(c *gin.Context) {
...
}      

參數格式說明

@Param state query int false "State"      

@Params 實際參數 query/path 類型 是否必須 别名

路由中初始化

package routers

import (
    ...

    _ "your_module_name/docs"

    ...
)

// InitRouter initialize routing information
func InitRouter() *gin.Engine {
    ...
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    ...

    return r
}      

生成

在項目根目錄執行

swag init      

執行完後,生成

Gloang Swagger——自動生産接口文檔

擷取線上接口文檔

 http://127.0.0.1:8000/swagger/index.html

Gloang Swagger——自動生産接口文檔