gin-swagger
- 下載 swagger
- 加載 swagger
- 執(zhí)行 swagger命令
- 使用Cors中間件
- 測試
1 下載swagger
go get -u github.com/swaggo/swag/cmd/swag
2 安裝swagger
安裝go-swagger杆逗,移動到下載的go-swagger包目錄(應(yīng)該是GOPATH/src/pkg/github.com/go-swagger,理解這個意思就好,路徑不一定對)。
go install ./cmd/swagger
測試是否安裝成功 cmd 執(zhí)行 swag -V 反饋 swag 版本
執(zhí)行后菊碟,會生成docs/doc.go以及docs/swagger.json,docs/swagger.yaml
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
2 加載 swagger
package router
import (
"gin_t/middelwares"
"gin_t/service"
"net/http"
"github.com/gin-gonic/gin"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
// @Tags 標(biāo)簽
// @Summary 標(biāo)題
// @description 描述,可以有多個
// @Success 200 {string} json "{"code":"200","data":"message":"string"}"
// @Router /ping [get]
func Router() *gin.Engine {
r := gin.Default()
r.Use(middelwares.Cors())
r.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// Swagger 配置
r.GET("swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
return r
}
package service
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Ping(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
}
package main
import (
_ "gin_t/docs"
"gin_t/router"
)
// @title API文檔
// @version 1.0
// @description API 文檔
// @host 127.0.0.01:8080
// @BasePath
func main() {
r := router.Router()
r.Run()
}
3 執(zhí)行 swagger命令
cmd 項目執(zhí)行 swag init
4 使用Cors中間件
package middelwares
import (
"fmt"
"strings"
"github.com/gin-gonic/gin"
)
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") //服務(wù)器支持的所有跨域請求的方法,為了避免瀏覽次請求的多次'預(yù)檢'請求
// 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")
// 允許跨域設(shè)置 可以返回其他子段
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") // 跨域關(guān)鍵設(shè)置 讓瀏覽器可以解析
c.Header("Access-Control-Max-Age", "172800") // 緩存請求信息 單位為秒
c.Header("Access-Control-Allow-Credentials", "false") // 跨域請求是否需要帶cookie信息 默認設(shè)置為true
c.Set("content-type", "application/json") // 設(shè)置返回格式是json
}
//放行所有OPTIONS方法
//if method == "OPTIONS" {
// c.JSON(http.StatusOK, "Options Request!")
//}
if method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
// 處理請求
c.Next() // 處理請求
}
}
5 測試
http://localhost:8080/swagger/index.html
swag注解開發(fā)方法
swagger主文件注解-通用API信息
注釋 | 說明 | 示例 |
---|---|---|
title | 必填 應(yīng)用程序的名稱纪吮。 | // @title Swagger Example API |
version | 必填 提供應(yīng)用程序API的版本呼伸。 | // @version 1.0 |
description | 應(yīng)用程序的簡短描述腔丧。 | // @description This is a sample server celler server. |
tag.name | 標(biāo)簽的名稱警没。 | // @tag.name This is the name of the tag |
tag.description | 標(biāo)簽的描述葫哗。 | // @tag.description Cool Description |
tag.docs.url | 標(biāo)簽的外部文檔的URL缔刹。 | // @tag.docs.url https://example.com |
tag.docs.description | 標(biāo)簽的外部文檔說明球涛。 | // @tag.docs.description Best example documentation |
termsOfService | API的服務(wù)條款。 | // @termsOfService http://swagger.io/terms/ |
contact.name | 公開的API的聯(lián)系信息校镐。 | // @contact.name API Support |
contact.url | 聯(lián)系信息的URL亿扁。 必須采用網(wǎng)址格式。 | // @contact.url http://www.swagger.io/support |
contact.email | 聯(lián)系人/組織的電子郵件地址灭翔。 必須采用電子郵件地址的格式魏烫。 | // @contact.email support@swagger.io |
license.name | 必填 用于API的許可證名稱。 | // @license.name Apache 2.0 |
license.url | 用于API的許可證的URL肝箱。 必須采用網(wǎng)址格式哄褒。 | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
host | 運行API的主機(主機名或IP地址)。 | // @host localhost:8080 |
BasePath | 運行API的基本路徑煌张。 | // @BasePath /api/v1 |
accept | API 可以使用的 MIME 類型列表呐赡。 請注意,Accept 僅影響具有請求正文的操作骏融,例如 POST链嘀、PUT 和 PATCH。 值必須如“Mime類型”中所述档玻。 | // @accept json |
produce | API可以生成的MIME類型的列表怀泊。值必須如“Mime類型”中所述。 | // @produce json |
query.collection.format | 請求URI query里數(shù)組參數(shù)的默認格式:csv误趴,multi霹琼,pipes,tsv凉当,ssv枣申。 如果未設(shè)置,則默認為csv看杭。 | // @query.collection.format multi |
schemes | 用空格分隔的請求的傳輸協(xié)議忠藤。 | // @schemes http https |
x-name | 擴展的鍵必須以x-開頭,并且只能使用json值 | // @x-example-key {“key”: “value”} |
每個API的注釋編寫-單個api
注釋 | 描述 |
---|---|
description | 操作行為的詳細說明楼雹。 |
description.markdown | 應(yīng)用程序的簡短描述模孩。該描述將從名為endpointname.md 的文件中讀取。 |
id | 用于標(biāo)識操作的唯一字符串贮缅。在所有API操作中必須唯一瓜贾。 |
tags | 每個API操作的標(biāo)簽列表,以逗號分隔携悯。 |
summary | 該操作的簡短摘要祭芦。 |
accept | API 可以使用的 MIME 類型列表。 請注意,Accept 僅影響具有請求正文的操作躁倒,例如 POST、PUT 和 PATCH越平。 值必須如“Mime類型”中所述昌跌。 |
produce | API可以生成的MIME類型的列表仰禀。值必須如“Mime類型”中所述。 |
param | 用空格分隔的參數(shù)蚕愤。param name ,param type ,data type ,is mandatory? ,comment attribute(optional)
|
security | 每個API操作的安全性答恶。 |
success | 以空格分隔的成功響應(yīng)。return code ,{param type} ,data type ,comment
|
failure | 以空格分隔的故障響應(yīng)萍诱。return code ,{param type} ,data type ,comment
|
response | 與success悬嗓、failure作用相同 |
header | 以空格分隔的頭字段。 return code ,{param type} ,data type ,comment
|
router | 以空格分隔的路徑定義裕坊。 path ,[httpMethod]
|
x-name | 擴展字段必須以x- 開頭包竹,并且只能使用json值。 |
//各個api.go
// GetProblemList
// @Tags 公共方法
// @Summary 問題列表
// @Param page query int false "page"
// @Param size query int false "size"
// @Param keyword query string false "keyword"
// @Param category_identity query string false "category_identity"
// @Success 200 {string} json "{"code":"200","data":""}"
// @Router /problem-list [get]
//各個api.go
// @Summary 支付列表
// @Description 獲取支付列表
// @Accept json
// @Produce json
// @param Authorization header string true "驗證參數(shù)Bearer和token空格拼接"
// @Param body body st.PaySearch true "交款查詢參數(shù)"
// @Success 200 {object} response.Response{data=st.PayListResponse}
// @Failure 500 {object} response.Response
// @Router /app/pay/list [post]
//main.go
// @title 這里寫標(biāo)題`
// @version 1.0`
// @description 這里寫描述信息`
// @termsOfService [http://swagger.io/terms/](http://swagger.io/terms/)`
// @contact.name 這里寫聯(lián)系人信息`
// @contact.url [http://www.swagger.io/support](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](http://www.apache.org/licenses/LICENSE-2.0.html)`
// @host 這里寫接口服務(wù)的host`
// @BasePath 這里寫base path`
//main.go
// @title API文檔
// @version 1.0
// @description API 文檔
// @host 127.0.0.01:8080
// @BasePath