github地址:https://github.com/swaggo/gin-swagger
下載安裝cmd/swag命令工具包
先下載cmd包,才能執行相關命令
go get -u github.com/swaggo/swag/cmd/swag
我開始沒成功,后來進入$GOPATH/bin/ 目錄執行go get github.com/swaggo/swag/cmd/swag ,在bin目錄下生成一個swag.exe文件,把$GOPATH/bin/ 添加到Path環境變量才算成功
執行初始化命令
swag init // 注意,一定要和main.go處於同一級目錄
初始化命令,在根目錄生成一個docs文件夾
- docs/docs.go
示例程序
package main import ( "apiwendang/controller" _ "apiwendang/docs" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) // @title Docker監控服務 // @version 1.0 // @description docker監控服務后端API接口文檔 // @contact.name API Support // @contact.url http://www.swagger.io/support // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host 127.0.0.1:9009 // @BasePath func main() { r := gin.New() r.Use(Cors()) //url := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition r.POST("/test/:id", controller.Test) r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) r.Run(":9009") } func Cors() gin.HandlerFunc { return func(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Next() } }
再次執行初始化命令
swag init // 注意,一定要和main.go處於同一級目錄
初始化命令,在根目錄生成一個docs文件夾,內含三個文件
- docs/docs.go
- swagger.json
- swagger.yaml
訪問swagger文檔:http://localhost:9009/swagger/index.html
====
API操作
// @Summary 接口概要說明 // @Description 接口詳細描述信息 // @Tags 用戶信息 //swagger API分類標簽, 同一個tag為一組 // @accept json //瀏覽器可處理數據類型,瀏覽器默認發 Accept: */* // @Produce json //設置返回數據的類型和編碼 // @Param id path int true "ID" //url參數:(name;參數類型[query(?id=),path(/123)];數據類型;required;參數描述) // @Param name query string false "name" // @Success 200 {object} Res {"code":200,"data":null,"msg":""} //成功返回的數據結構, 最后是示例 // @Failure 400 {object} Res {"code":200,"data":null,"msg":""} // @Router /test/{id} [get] //路由信息,一定要寫上
如果參數是body
// @Param user body models.User true "user"
1. 返回字符串
// @Summary 測試接口 // @Description 描述信息 // @Success 200 {string} string "ok" // @Router / [get] func Test(ctx *gin.Context) { ctx.JSON(200, "ok") }
2. 返回gin.H
// @Summary 測試接口 // @Description 描述信息 // @Success 200 {object} gin.H // @Router / [get] func Test(ctx *gin.Context) { ctx.JSON(200, gin.H{ "code":200, }) }
如果直接返回gin.H這種json結構,要用@Success 200 {object} gin.H,但是這種編譯很慢,最好還是返回一種固定的結構體
3. 返回固定struct結構體
type Res struct { Code int `json:"code"` Data interface{} `json:"data"` Msg string `json:"msg"` } func returnMsg(ctx *gin.Context, code int, data interface{}, msg string) { ctx.JSON(200, Res{ Code:code, Data:data, Msg:msg, }) } // @Summary 測試接口 // @Description 描述信息 // @Success 200 {object} Res {"code":200,"data":null,"msg":""} // @Router / [get] func Test(ctx *gin.Context) { ctx.JSON(200, Res{ Code:200, Data:nil, Msg:"", }) }
POST請求:
models/user.go type User struct { ID int `json:"id"` Name string `json:"name"` } ================== type Res struct { Code int `json:"code"` Data interface{} `json:"data"` Msg string `json:"msg"` } func returnMsg(ctx *gin.Context, code int, data interface{}, msg string) { ctx.JSON(200, Res{ Code:code, Data:data, Msg:msg, }) } func Test1(ctx *gin.Context) { returnMsg(ctx, 500, "aaa", "bbb") } // @Summary 接口概要說明 // @Description 接口詳細描述信息 // @Tags 測試 // @Security Bearer // @Produce json // @Param id path int true "ID" // @Param user body models.User true "user" // @Success 200 {object} Res {"code":200,"data":null,"msg":""} // @Router /test/{id} [post] func Test(ctx *gin.Context) { fmt.Println(ctx.Param("id")) var input models.User if err := ctx.ShouldBindJSON(&input); err!=nil{ returnMsg(ctx, 402, nil, err.Error()) return } fmt.Println(input) returnMsg(ctx, 200, "aaa", "bbb") }
如果出現錯誤:Undocumented TypeError: Failed to fetch
查看具體錯誤信息,瀏覽器F12,發現是跨域問題:
Failed to load http://127.0.0.1:9009/test/2: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9009' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
設置允許跨域就OK了
簡單版本:
func Cors() gin.HandlerFunc { return func(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Next() } }
復雜的可以根據實際需求添加:
func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method origin := c.Request.Header.Get("Origin") var headerKeys []string for k, _ := range c.Request.Header { headerKeys = append(headerKeys, k) } headerStr := strings.Join(headerKeys, ", ") if headerStr != "" { headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr) } else { headerStr = "access-control-allow-origin, access-control-allow-headers" } if origin != "" { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Origin", "*") // 這是允許訪問所有域 c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服務器支持的所有跨域請求的方法,為了避免瀏覽次請求的多次'預檢'請求 // header的類型 c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma") // 允許跨域設置 可以返回其他子段 c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域關鍵設置 讓瀏覽器可以解析 c.Header("Access-Control-Max-Age", "172800") // 緩存請求信息 單位為秒 c.Header("Access-Control-Allow-Credentials", "false") // 跨域請求是否需要帶cookie信息 默認設置為true c.Set("content-type", "application/json") // 設置返回格式是json } //放行所有OPTIONS方法 //if method == "OPTIONS" { // c.JSON(http.StatusOK, "Options Request!") //} if method == "OPTIONS" { c.AbortWithStatus(204) return } // 處理請求 c.Next() // 處理請求 } }
https://www.ctolib.com/swaggo-swag.html
https://github.com/swaggo/swag
原文 https://www.cnblogs.com/zhzhlong/p/11800787.html