goswagger github倉庫
https://github.com/swaggo/swag
安裝 swag cli
1.因為網絡原因,先安裝gopm 管理工具
go get -v -u github.com/gpmgo/gopm
安裝到了 $GOPTH/bin里 找不到的話,用 sudo find / -name gopm 找一下
2.安裝swag
gopm get -g -v github.com/swaggo/swag/cmd/swag
過程中可能會報錯,重試即可
3.找到 swag ( find / -name swag ====》 cd /go/src/github.com/swaggo/swag/cmd/swag/) 會看到main.go 文件
4 執行:go install (可能會報錯缺少包,挨個安裝 go get -u github.com/urfave/cli)
5 再次執行 go install
不出意外的話,swag安裝成功了
找到swag執行文件,應該在$GOPTH/bin里面,然后加成全局變量( sudo cp swag /usr/local/go/bin/)
然后試一下swag -version
lhs:redigo houlv$ swag -version swag version v1.6.2
成功!
在golang-gin項目上集成swagger
找到main函數所在的類
添加以下代碼
import里
swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" _ "testsu.cn/rocket/docs"
其中docs是你生成docs的路徑
面函數里實現
g.Go(func() error { r := gin.New() url := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) r.Run() return nil })
go.mod里添加
github.com/swaggo/gin-swagger v1.2.1-0.20190717074206-d488a692749f github.com/swaggo/swag v1.5.1
在API handler文件里添加標准注解
例如:
// @Summary 生成pdf文檔 // @Description 傳遞id生成pdf文檔 // @Accept json // @Param id path int true "id" // @Success 200 {object} model.VersionDTO // @Failure 500 {string} json "{"code":500,"data":{},"msg":"ok"}" // @Router /report/{id}/pdf/download [get] func (handler *TestcaseReportHtml) DownloadTestCasePDF(c *gin.Context) {
然后在項目的根目錄執行
swag init -g launcher/api-rocket/web.go
-g 后面所跟的為main方法在的位置
之后將項目跑起來,訪問地址:
http://localhost:8080/swagger/index.html
即可看到自動生成的文檔
入截圖所示:
最后添加:將swagger的標准庫添加上:
標准注釋
https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html