Iris-go 集成swagger


Iris-go 集成swagger

swagger官方文檔https://github.com/iris-contrib/swagger

1.安裝swgger

配置代理
go env -w GOPROXY=https://goproxy.cn,direct

go get -u github.com/swaggo/swag/cmd/swag

go get github.com/iris-contrib/swagger/v12@v12.2.0-alpha

swag -version

2.初始化

在main.go的同級目錄執行

swag init

會生成3個文件docs.go swagger.json swagger.yaml

3.在main.go中配置注釋

// swagger middleware for Iris
// swagger embed files

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

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

// @host localhost:8085
// @BasePath /vue

4.在路由文件routes.go中加入下列代碼

            // swagger配置方法一:其他文檔
		config := swagger.Config{
            // 指向swagger init生成文檔的路徑
			URL:          "http://www.xxx.com/swagger/doc.json",
			DeepLinking:  true,

		}
		app.Get("/swagger/*any", swagger.CustomWrapHandler(&config,swaggerFiles.Handler))
           // swagger配置方法二:默認文檔
           app.Get("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler))

5.使用官方注釋配置接口

官方注釋文檔https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html

例子:

// @Summary 獲取學生列表
// @Description 
// @Tags 學生
// @Accept application/json
// @Produce application/json
// @Param Authorization header string true "Bearer token"
// @Param object query models.student false "查詢參數"
// @Param name query string true "name"
// @Param body body st.PaySearch true "交款查詢參數"
// @Param tel query string true "tel"
// @Success 200 {object} models.Result
// @Failure 400 {object} models.Result
// @Router /student/list [get/post]
func getStudentList(ctx iris.Context) {
.....
}

6.重新生成swagger文檔

每當接口注釋寫完后,都需要執行命令

swag init -g main.go

7.啟動項目,訪問http://localhost:8085/swagger/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM