swaggos 是一個golang版本的swagger文檔生成器,提供了native code包裝器,並且支持主流的web框架包裹器
github 地址:https://github.com/swaggo/gin-swagger
下載安裝 swag
$ go get -u github.com/swaggo/swag/cmd/swag
在Go項目根文件夾中運行Swag
在
main.go
所在目錄執行swag init
, -g 參數是輸出詳細信息執行后,會生成docs/doc.go以及docs/swagger.json,docs/swagger.yaml
$ swag init
下載gin-swagger
$ go get -u github.com/swaggo/gin-swagger
$ go get -u github.com/swaggo/files
然后在路由文件引入
import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
添加訪問文檔路由
// swage 文檔訪問路由\n
eng := gin.Default()
eng.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
注釋參數
-
注釋詳細格式參考:https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html
-
主程序注釋(main.go)
// @title Golang Esign API // @version 1.0 // @description Golang api of demo // @termsOfService http://github.com // @contact.name API Support // @contact.url http://www.cnblogs.com // @contact.email ×××@qq.com //@host 127.0.0.1:8081 func main() { }
-
控制器注釋(congroller.go)
-
Get 參數方法
type GetOperationLogListResponse struct { List *[]model.OperationLog `json:"list"` Total int `json:"total"` } // @Title 應用中心操作日志 // @Author mengyilingjian@outlook.com // @Description 獲取應用中心操作日志 // @Tags operationlog // @Param Authorization header string true "Bearer 31a165baebe6dec616b1f8f3207b4273" // @Param route formData string false "路由" // @Param operator formData string false "操作者" // @Param operation_type formData string false "操作類型 1 新增、2 刪除、3 更新" // @Param description formData string false "操作描述" // @Param start_time formData string false "開始時間" // @Param end_time formData string false "結束時間" // @Param page formData string true "頁數" // @Param size formData string true "數據條數" // @Success 200 {object} GetOperationLogListResponse // @Router /api/v1/app/operationlog/appcenter [get] func GetOperationLogList(c *gin.Context) { }
以上生成文檔格式如下:
-
Post 參數方法
ReleaseTemplateAdd struct { Name string `json:"name"` DeployEnv string `json:"deploy_env"` GitlabType int `json:"gitlab_type"` GitlabBranchName string `json:"gitlab_branch_name"` IsAutoRelease int `json:"is_auto_release"` Description string `json:"description"` GitlabCITemplateID int32 `json:"gitlab_ci_template_id"` GitlabID uint32 `json:"gitlab_id"` } // @Title 新增模版 // @Author mengyilingjian@outlook.com // @Description 新增模版 // @Tags release template // @Param Authorization header string true "Bearer 31a165baebe6dec616b1f8f3207b4273" // @Param body body ReleaseTemplateAdd true "JSON數據" // @Success 200 {object} handler.ReportJSONResult // @Router /api/v1/release/template/add [post] func ReleaseTemplateAdd(c *gin.Context){ }
以上生成格式文檔如下:
-