Golang 生成 swagger 文檔
【導讀】swagger 工具和 golang 如何深度聯動?本文介紹了 swaggos 文檔生成器。
golang 生成 swagger 文檔一直沒有很好的方式,官方推薦的是通過註釋生成文檔,但是缺陷是註釋很難寫,IDE 又沒有自動提示
今天發現一款不錯的三方包,可以直接基於 golang 代碼生成文檔
github.com/clearcodecn/swaggos
Swaggos
swaggos 是一個 golang 版本的 swagger 文檔生成器,提供了 native code 包裝器。
安裝
go get -u github.com/clearcodecn/swaggos
使用
創建實例
創建一個新的實例,配置一些基本信息
host
和apiPrefix
doc := swaggos.Default()
doc.HostInfo("www.github.com","/api/v1")
// default is application/json
doc.Produces("application/json")
// default is application/json
doc.Consumes("application/json")
Authorization
項目支持 swagger 的所有鑑權方式:oauth2
, basic auth
, apiKey
Oauth2
var scopes = []string{"openid"}
var tokenURL = "https://yourtokenurl"
var authURL = "https://yourAuthURL"
// config password flow
doc.Oauth2Password(tokenURL,scopes)
// access code
doc.Oauth2AccessCode(authURL,tokenURL,scopes)
// client
doc.Oauth2Client(tokenURL,scopes)
// implicit
doc.Oauth2Implicit(authURL,scopes)
Basic Auth
doc.Basic()
自定義 Token
會在 header 中增加
access_token
參數
doc.JWT("access_token")
公共參數
// will create header param in each request
doc.Header("name","description",true)
doc.Query("name","description",true)
doc.Form("name","description",true)
請求路勁
path 是一個請求的實例,支持流式寫法。
// 創建一個 path
path := doc.Get("user_information")
path.
Tag("tagName"). // 創建 tag
Summary("summary"). // 總結
Description("...."). // 描述
ContentType("application/json","text/html"). // 請求/響應類型
// path params
path.Form("key",swaggos.Attribute{})
// form files
path.FormFile("file",swaggos.Attribute{Required:true})
// form object reference
path.FormObject(new(User))
// query object
path.QueryObject(new(User))
// body
path.Body(new(User))
// json response
path.JSON(new(User))
// Attribute rules:
type Attribute struct {
Model string `json:"model"` // key name
Description string `json:"description"` // description
Required bool `json:"required"` // if it's required
Type string `json:"type"` // the param type
Example interface{} `json:"example"` // example value
Nullable bool `json:"nullable,omitempty"` // if it's nullable
Format string `json:"format,omitempty"` // format
Title string `json:"title,omitempty"` // title
Default interface{} `json:"default,omitempty"` // default value
Maximum *float64 `json:"maximum,omitempty"` // max num
Minimum *float64 `json:"minimum,omitempty"` // min num
MaxLength *int64 `json:"maxLength,omitempty"` // max length
MinLength *int64 `json:"minLength,omitempty"` // min length
Pattern string `json:"pattern,omitempty"` // regexp pattern
MaxItems *int64 `json:"maxItems,omitempty"` // max array length
MinItems *int64 `json:"minItems,omitempty"` // min array length
Enum []interface{} `json:"enum,omitempty"` // enum values
Ignore bool `json:"ignore"` // if it's ignore
Json string `json:"json"` // key name
}
路勁響應
// 響應 json,創建 model
path.JSON(new(Response))
// will provide a example response
// 400
path.BadRequest(map[string]interface{
"data": nil,
"code": 400,
})
// 401
path.UnAuthorization(v)
// 403
path.Forbidden(v)
// 500
path.ServerError(v)
分組
分組將對 api 進行分組,組下面的所有路勁會共享分組的公共參數
g := doc.Group("/api/v2")
g.Get("/user") // --> /api/v2/user
// ... other methods
g.Form ...
g.Query ...
g.Header ...
全局響應
doc.Response(200, new(Success))
doc.Response(400, new(Fail))
doc.Response(500, new(ServerError))
結構體的 tag 支持
type User struct {
// 字段名稱 model > json
// this example field name will be m1
ModelName string `model:"m1" json:"m2"`
// 字段名會是 username
Username string `json:"username"`
// 字段名會是 Password
Password string
// 會被忽略
Ignored `json:"-"`
// 是否必須
Required string `required:"true"`
// 字段的描述
Description string `description:"this is description"`
// 字段的類型:string,integer,time,number,boolean,array...
Type string `type:"time"`
// 默認值 abc
DefaultValue string `default:"abc"`
// 最大值 100
Max float64 `maximum:"100"`
// 最小值 0
Min float64 `min:"0"`
// 最大長度 20
MaxLength string `maxLength:"20"`
// 最小長度 10
MinLength string `minLength:"10"`
// 正則表達式規則
Pattern string `pattern:"\d{0,9}"`
// 數組長度 小於 3
MaxItems []int `maxItems:"3"`
// 數組長度大於 3
MinItem []int `minItems:"3"`
// 枚舉,用 , 分割
EnumValue int `enum:"a,b,c,d"`
// 忽略字段
IgnoreField string `ignore:"true"`
// 匿名字段規則:
// 如果是一個基本類型,則直接添加,
// 如果是一個 數組,也將直接添加
// 如果是一個結構體 但是帶了 json tag,將會作爲一個字段
// 如果是一個結構體 帶沒有 json tag,將會將裏面的子字段添加上該結構體上
Anonymous
}
構建 json 和 yaml
data,_ := doc.Build()
fmt.Println(string(data))
=> this is the swagger schema in json format
data,_ := doc.Yaml()
fmt.Println(string(data))
=> yaml format
提供 http 服務
http.Handle("/swagger",doc)
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/ygvx62CqrZqcuYpdTat-7A