?英語∙簡體中文português
贓物將註釋轉換為Swagger Document 2.0。我們為流行的GO Web框架創建了各種插件。這使您可以快速與現有的GO項目(使用Swagger UI)集成。
將註釋添加到您的API源代碼,請參閱聲明評論格式。
使用以下方式安裝贓物:
go install github.com/swaggo/swag/cmd/swag@latest
要從源構建,您需要GO(1.19或更新)。
另外,您可以運行Docker映像:
docker run --rm -v $( pwd ) :/code ghcr.io/swaggo/swag:latest
或從發布頁面下載預編譯的二進製文件。
swag init
,其中包含main.go
文件。這將解析您的評論並生成所需的文件( docs
文件夾和docs/docs.go
)。 swag init
確保導入生成的docs/docs.go
以便您的特定配置獲得init
。如果您的一般API註釋-g
main.go
中。
import _ "example-module-name/docs"
swag init -g http/api.go
swag fmt
格式贓物評論。 (請升級到最新版本) swag fmt
swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--quiet, -q Make the logger quiet. (default: false)
--generalInfo value, -g value Go file path in which ' swagger general API Info ' is written (default: " main.go " )
--dir value, -d value Directories you want to parse,comma separated and general-info file must be in the first one (default: " ./ " )
--exclude value Exclude directories and files when searching, comma separated
--propertyStrategy value, -p value Property Naming Strategy like snakecase,camelcase,pascalcase (default: " camelcase " )
--output value, -o value Output directory for all the generated files(swagger.json, swagger.yaml and docs.go) (default: " ./docs " )
--outputTypes value, --ot value Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml (default: " go,json,yaml " )
--parseVendor Parse go files in ' vendor ' folder, disabled by default (default: false)
--parseDependency, --pd Parse go files inside dependency folder, disabled by default (default: false)
--parseDependencyLevel, --pdl Enhancement of ' --parseDependency ' , parse go files inside dependency folder, 0 disabled, 1 only parse models, 2 only parse operations, 3 parse all (default: 0)
--markdownFiles value, --md value Parse folder containing markdown files to use as description, disabled by default
--codeExampleFiles value, --cef value Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
--parseInternal Parse go files in internal packages, disabled by default (default: false)
--generatedTime Generate timestamp at the top of docs.go, disabled by default (default: false)
--parseDepth value Dependency parse depth (default: 100)
--requiredByDefault Set validation required for all fields by default (default: false)
--instanceName value This parameter can be used to name different swagger document instances. It is optional.
--overridesFile value File to read global type overrides from. (default: " .swaggo " )
--parseGoList Parse dependency via ' go list ' (default: true)
--tags value, -t value A comma-separated list of tags to filter the APIs for which the documentation is generated.Special case if the tag is prefixed with the ' ! ' character then the APIs with that tag will be excluded
--templateDelims value, --td value Provide custom delimiters for Go template generation. The format is leftDelim,rightDelim. For example: " [[,]] "
--collectionFormat value, --cf value Set default collection format (default: " csv " )
--state value Initial state for the state machine (default: " " ), @HostState in root file, @State in other files
--parseFuncBody Parse API info within body of functions in go files, disabled by default (default: false)
--help, -h show help (default: false)
swag fmt -h
NAME:
swag fmt - format swag comments
USAGE:
swag fmt [command options] [arguments...]
OPTIONS:
--dir value, -d value Directories you want to parse,comma separated and general-info file must be in the first one (default: " ./ " )
--exclude value Exclude directories and files when searching, comma separated
--generalInfo value, -g value Go file path in which ' swagger general API Info ' is written (default: " main.go " )
--help, -h show help (default: false)
在此處找到示例源代碼。
完成入門的步驟
swag init
生成Swagger 2.0文檔後,導入以下軟件包: import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
main.go
代碼中添加常規API註釋: // @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main () {
r := gin . Default ()
c := controller . NewController ()
v1 := r . Group ( "/api/v1" )
{
accounts := v1 . Group ( "/accounts" )
{
accounts . GET ( ":id" , c . ShowAccount )
accounts . GET ( "" , c . ListAccounts )
accounts . POST ( "" , c . AddAccount )
accounts . DELETE ( ":id" , c . DeleteAccount )
accounts . PATCH ( ":id" , c . UpdateAccount )
accounts . POST ( ":id/images" , c . UploadAccountImage )
}
//...
}
r . GET ( "/swagger/*any" , ginSwagger . WrapHandler ( swaggerFiles . Handler ))
r . Run ( ":8080" )
}
//...
另外,可以動態設置一些一般的API信息。生成的代碼軟件包docs
導出了SwaggerInfo
變量,我們可以用來以編程方式設置標題,描述,版本,主機和基本路徑。使用杜松子酒的例子:
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main () {
// programmatically set swagger info
docs . SwaggerInfo . Title = "Swagger Example API"
docs . SwaggerInfo . Description = "This is a sample server Petstore server."
docs . SwaggerInfo . Version = "1.0"
docs . SwaggerInfo . Host = "petstore.swagger.io"
docs . SwaggerInfo . BasePath = "/v2"
docs . SwaggerInfo . Schemes = [] string { "http" , "https" }
r := gin . New ()
// use ginSwagger middleware to serve the API docs
r . GET ( "/swagger/*any" , ginSwagger . WrapHandler ( swaggerFiles . Handler ))
r . Run ()
}
controller
代碼中添加API操作註釋 package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func ( c * Controller ) ShowAccount ( ctx * gin. Context ) {
id := ctx . Param ( "id" )
aid , err := strconv . Atoi ( id )
if err != nil {
httputil . NewError ( ctx , http . StatusBadRequest , err )
return
}
account , err := model . AccountOne ( aid )
if err != nil {
httputil . NewError ( ctx , http . StatusNotFound , err )
return
}
ctx . JSON ( http . StatusOK , account )
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func ( c * Controller ) ListAccounts ( ctx * gin. Context ) {
q := ctx . Request . URL . Query (). Get ( "q" )
accounts , err := model . AccountsAll ( q )
if err != nil {
httputil . NewError ( ctx , http . StatusNotFound , err )
return
}
ctx . JSON ( http . StatusOK , accounts )
}
//...
swag init
贓物評論可以自動格式化,就像“ go fmt”一樣。在此處找到格式化的結果。
用法:
swag fmt
排除文件夾:
swag fmt -d ./ --exclude ./internal
使用swag fmt
時,您需要確保對該功能有DOC評論,以確保正確格式。這是由於swag fmt
縮進的贓物評論帶有標籤,只有在標准文檔評論後才允許。
例如,使用
// ListAccounts lists all existing accounts
//
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func ( c * Controller ) ListAccounts ( ctx * gin. Context ) {
Swagger 2.0文檔
示例Celler/main.go
註解 | 描述 | 例子 |
---|---|---|
標題 | 必需的。應用程序的標題。 | // @Title Swagger示例API |
版本 | 必需的。提供應用程序API的版本。 | // @version 1.0 |
描述 | 該應用程序的簡短描述。 | // @description這是一個示例服務器電池服務器。 |
tag.name | 標籤的名稱。 | // @tag.name這是標籤的名稱 |
tag.Description | 標籤的描述 | // @tag.Description Cool說明 |
tag.docs.url | 標籤外部文檔的URL | // @tag.docs.url https://example.com |
tag.docs.docs.doscription | 標籤外部文檔的描述 | // @tag.docs.description最佳示例文檔 |
服務條款 | API的服務條款。 | // @@termsofService http://swagger.io/terms/ |
contact.name | 暴露的API的聯繫信息。 | // @contact.name API支持 |
contact.url | URL指向聯繫信息。必須採用URL的格式。 | // @contact.url http://www.swagger.io/support |
contact.Email | 聯繫人/組織的電子郵件地址。必須採用電子郵件地址的格式。 | // @contact.email支持 @swagger.io |
許可證。名稱 | 必需的。 API使用的許可名稱。 | // @license.name apache 2.0 |
許可 | 用於API的許可證的URL。必須採用URL的格式。 | // @lince.url http://www.apache.org/licenses/license-2.0.html |
主持人 | 服務API的主機(名稱或IP)。 | // @host localhost:8080 |
基礎 | 提供API的基本路徑。 | // @basepath/api/v1 |
接受 | API可以消耗的MIME類型列表。請注意,接受只會影響請求主體(例如郵政,put和patch)的操作。值必須如MIME類型所述所述。 | // @accept json |
生產 | API可以產生的MIME類型列表。值必須如MIME類型所述所述。 | // @produce json |
query.collection.format | 查詢,枚舉:CSV,Multi,Pipes,TSV,SSV中的默認集合(數組)param格式。如果未設置,則CSV為默認值。 | // @query.collection.format multi |
方案 | 由空間隔開的操作的傳輸協議。 | // @schemes http https |
externalDocs.Description | 外部文檔的描述。 | // @ @externalDocs.Description OpenAPI |
externaldocs.url | 外部文檔的URL。 | // @ @externaldocs.url https://swagger.io/resources/open-api/ |
x-name | 擴展密鑰必須以X-的啟動,僅命令JSON值 | // @ @x-example-key {“ key”:“ value”} |
當您的文檔中的短字符串不足,或者您需要圖像,代碼示例和類似的內容時,您可能需要使用Markdown說明。為了使用Markdown說明,請使用以下註釋。
註解 | 描述 | 例子 |
---|---|---|
標題 | 必需的。應用程序的標題。 | // @Title Swagger示例API |
版本 | 必需的。提供應用程序API的版本。 | // @version 1.0 |
description.markdown | 該應用程序的簡短描述。從api.md文件中解析。這是@Description的替代品 | // @descript |
tag.name | 標籤的名稱。 | // @tag.name這是標籤的名稱 |
tag.description.markdown | 標籤的描述這是標籤的替代方案。描述將從名為tagname.md的文件中讀取 | // @tag.description.markdown |
tag.x-name | 擴展密鑰必須以x-開始,僅命令字符串值 | // @x-example-key值 |
示例Celler/Controller
註解 | 描述 |
---|---|
描述 | 對操作行為的詳細解釋。 |
description.markdown | 該應用程序的簡短描述。描述將從文件中讀取。例如@description.markdown details 將加載details.md |
ID | 用於識別操作的獨特字符串。在所有API操作中必須是唯一的。 |
標籤 | 每個API操作的標籤列表,該標籤由逗號分隔。 |
概括 | 簡短的摘要有關操作的作用。 |
接受 | API可以消耗的MIME類型列表。請注意,接受只會影響請求主體(例如郵政,put和patch)的操作。值必須如MIME類型所述所述。 |
生產 | API可以產生的MIME類型列表。值必須如MIME類型所述所述。 |
參數 | 由空間隔開的參數。 param name , param type , data type is mandatory? , comment attribute(optional) |
安全 | 每個API操作的安全性。 |
成功 | 由空間分開的成功響應。 return code or default , {param type} , data type , comment |
失敗 | 被空間分開的故障響應。 return code or default , {param type} , data type , comment |
回覆 | 與success 和failure 一樣 |
標題 | 標題是由空間隔開的響應。 return code , {param type} , data type , comment |
路由器 | 路徑定義被空間分開。 path , [httpMethod] |
棄用者 | 與路由器一樣,但棄用。 |
x-name | 擴展密鑰必須以X-的速度開始,並僅取JSON值。 |
x-codeSample | 可選的降壓用法。將file 作為參數。然後,這將搜索給定文件夾中的摘要所稱的文件。 |
棄用 | 將端點標記為棄用。 |
swag
接受所有以正確格式的MIME類型,即匹配*/*
。除此之外, swag
還接受某些MIME類型的別名,如下所示:
別名 | 啞劇類型 |
---|---|
JSON | 應用程序/JSON |
XML | 文本/XML |
清楚的 | 文字/平原 |
html | 文本/html |
MPFD | Multipart/form-data |
X www-Form-urlenced | 應用/X-WWW-Form-urlenCoded |
JSON-API | 應用程序/vnd.api+json |
Json-stream | 應用程序/X-JSON-stream |
八位字節 | 應用程序/八位格流 |
PNG | 圖像/PNG |
jpeg | 圖像/jpeg |
GIF | 圖像/gif |
註解 | 描述 | 參數 | 例子 |
---|---|---|---|
SecurityDefinitions.basic | 基本驗證。 | // @SecurityDefinitions.basic BasicAuth | |
SecurityDefinitions.apikey | API鍵auth。 | 在,名稱,描述 | // @SecurityDefinitions.apikey Apikeyauth |
SecurityDefinitions.oauth2.Application | OAuth2應用程序auth。 | Tokenurl,範圍,描述 | // @securityDefinitions.oauth2.application oauth2application |
SecurityDefinitions.oauth2.implicit | OAuth2隱式驗證。 | 授權圖,範圍,描述 | // @securityDefinitions.oauth2.implitic oauth2implicit |
securityDefinitions.oauth2.password | OAuth2密碼驗證。 | Tokenurl,範圍,描述 | // @securityDefinitions.oauth2.password oauth2password |
SecurityDefinitions.oauth2.AccessCode | OAuth2訪問代碼驗證。 | tokenurl,授權庫,範圍,描述 | // @securityDefinitions.oauth2.accesscode oauth2accesscode |
參數註釋 | 例子 |
---|---|
在 | // @ @header |
姓名 | // @name授權 |
Tokenurl | // @tokenurl https://example.com/oauth/token |
授權圖 | // @authorizationurl https://example.com/oauth/authorize |
範圍 | // @scope.write贈款寫訪問 |
描述 | // @Description Oauth保護我們的實體終點 |
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
它還適用於結構字段:
type Foo struct {
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux [] string `enums:"foo,bar,baz"`
}
字段名稱 | 類型 | 描述 |
---|---|---|
證實 | string | 確定參數的驗證。可能的值是: required,optional 。 |
預設 | * | 聲明如果沒有提供服務器將使用的參數的值,例如,如果客戶端在請求中未提供的“計數”以控制每個頁面的結果數可能默認為100。 (注意:“默認值”對所需參數沒有任何含義。)請參見https://tools.ietf.org/html/draft-fge-json-schemo-validation-validation-00#section-6.2。與JSON模式不同,該值必須符合此參數的定義type 。 |
最大限度 | number | 請參閱https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2。 |
最低限度 | number | 請參閱https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3。 |
多層 | number | 請參閱https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1。 |
最大長度 | integer | 請參閱https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1。 |
最小長度 | integer | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2。 |
枚舉 | [*] | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1。 |
格式 | string | 上述type 的擴展格式。有關更多詳細信息,請參見數據類型格式。 |
CollectionFormat | string | 如果使用類型數組,則確定數組的格式。可能的值是:
csv 。 |
例子 | * | 聲明參數值的示例 |
擴展 | string | 將擴展名添加到參數。 |
字段名稱 | 類型 | 描述 |
---|---|---|
圖案 | string | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3。 |
最大值 | integer | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2。 |
Minitems | integer | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3。 |
唯一材料 | boolean | 參見https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4。 |
您可以在常規API描述中添加跨越多行的描述或類似的路由定義:
// @description This is the first line
// @description This is the second line
// @description And so forth.
// @Success 200 {array} model.Account <-- This is a user defined struct.
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
您可以在功能主體內聲明您的請求響應結構。您必須遵循命名約定<package-name>.<function-name>.<struct-name>
。
package main
// @Param request body main.MyHandler.request true "query params"
// @Success 200 {object} main.MyHandler.response
// @Router /test [post]
func MyHandler () {
type request struct {
RequestField string
}
type response struct {
ResponseField string
}
}
// JSONResult's data field will be overridden by the specific type proto.Order
@ success 200 { object } jsonresult. JSONResult { data = proto . Order } "desc"
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface {} `json:"data"`
}
type Order struct { //in `proto` package
Id uint `json:"id"`
Data interface {} `json:"data"`
}
@ success 200 { object } jsonresult. JSONResult { data = []proto. Order } "desc"
@ success 200 { object } jsonresult. JSONResult { data = string } "desc"
@ success 200 { object } jsonresult. JSONResult { data = [] string } "desc"
@ success 200 { object } jsonresult. JSONResult { data1 = string , data2 = [] string , data3 = proto . Order , data4 = []proto. Order } "desc"
type DeepObject struct { //in `proto` package
...
}
@ success 200 { object } jsonresult. JSONResult { data1 = proto. Order { data = proto . DeepObject }, data2 = []proto. Order { data = []proto. DeepObject }} "desc"
// @Param X-MyHeader header string true "MyHeader must be set for valid response"
// @Param X-API-VERSION header string true "API version eg.: 1.0"
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
/// ...
// @Param group_id path int true "Group ID"
// @Param user_id path int true "User ID"
// ...
// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
// @Router /examples/user/{user_id}/address [put]
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls [] string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
// @Param email body string true "message/rfc822" SchemaExample(Subject: TestmailrnrnBody Messagern)
// Account model info
// @Description User account information
// @Description with user id and username
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
#708解析器僅處理以@Description
屬性開頭的結構註釋。但是它按原樣寫入所有結構字段評論。
因此,產生的Swagger Doc如下:
"Account" : {
"type" : " object " ,
"description" : " User account information with user id and username "
"properties" : {
"id" : {
"type" : " integer " ,
"description" : " ID this is userid "
},
"name" : {
"type" : " string " ,
"description" : " This is Name "
}
}
}
#201
type TimestampTime struct {
time. Time
}
///implement encoding.JSON.Marshaler interface
func ( t * TimestampTime ) MarshalJSON () ([] byte , error ) {
bin := make ([] byte , 16 )
bin = strconv . AppendInt ( bin [: 0 ], t . Time . Unix (), 10 )
return bin , nil
}
func ( t * TimestampTime ) UnmarshalJSON ( bin [] byte ) error {
v , err := strconv . ParseInt ( string ( bin ), 10 , 64 )
if err != nil {
return err
}
t . Time = time . Unix ( v , 0 )
return nil
}
///
type Account struct {
// Override primitive type by simply specifying it via `swaggertype` tag
ID sql. NullInt64 `json:"id" swaggertype:"integer"`
// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big. Float `json:"coeffs" swaggertype:"array,number"`
}
#379
type CerticateKeyPair struct {
Crt [] byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key [] byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
產生的Swagger文檔如下:
"api.MyBinding" : {
"type" :" object ",
"properties" :{
"crt" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
},
"key" :{
"type" :" string ",
"format" :" base64 ",
"example" :" U3dhZ2dlciByb2Nrcw == "
}
}
}
如果您使用的是生成的文件,則可能是swaggertype
swaggerignore
。
通過將映射傳遞給贓物--overridesFile
您可以告訴贓物在出現的任何一種類型中都代替另一種類型。默認情況下,如果當前目錄中存在.swaggo
文件,則將使用。
GO代碼:
type MyStruct struct {
ID sql. NullInt64 `json:"id"`
Name sql. NullString `json:"name"`
}
.swaggo
:
// Replace all NullInt64 with int
replace database/sql.NullInt64 int
// Don't include any fields of type database/sql.NullString in the swagger docs
skip database/sql.NullString
可能的指令是註釋(以//
開頭), replace path/to/a.type path/to/b.type
,然後skip path/to/a.type
。
(請注意,當多個軟件包定義具有相同名稱的類型時,必須提供任何命名類型的完整路徑)
渲染:
"types.MyStruct" : {
"id" : "integer"
}
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
產生Swagger Doc如下:
"Account" : {
"type" : "object" ,
"properties" : {
"id" : {
"type" : "string" ,
"x-nullable" : true ,
"x-abc" : "def" ,
"x-omitempty" : false
}
}
}
type Resp struct {
Code int
} //@name Response
一般API信息。
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
每個API操作。
// @Security ApiKeyAuth
使它或條件
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
使它和條件
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
默認情況下, swag
命令在三種不同的文件/文件類型中生成Swagger規範:
如果您想限制一組應該生成的文件類型,則可以使用--outputTypes
(short -ot
)標誌。默認值是go,json,yaml
輸出類型與逗號分隔。要限制輸出只能go
和yaml
文件,您會寫go,yaml
。使用完整的命令,將是swag init --outputTypes go,yaml
。
// @Success 200 {object} web.GenericNestedResponse[types.Post]
// @Success 204 {object} web.GenericNestedResponse[types.Post, Types.AnotherOne]
// @Success 201 {object} web.GenericNestedResponse[web.GenericInnerType[types.Post]]
func GetPosts ( w http. ResponseWriter , r * http. Request ) {
_ = web. GenericNestedResponse [types. Post ]{}
}
有關更多詳細信息和其他示例,請參見此文件。
#980#1177
如果您的宣傳註釋或結構字段包含“ {{”或“}}”,則模板生成很可能會失敗,因為這些是GO模板的默認分隔線。
為了使一代正常工作,您可以使用-td
更改默認的分界符。例如:
swag init -g http/api.go -td "[[,]]"
新的定界符是帶有“ <left delimiter>
, <right delimiter>
”的格式的字符串。
如果結構是在依賴關係軟件包中定義的,請使用--parseDependency
。
如果在您的主項目中定義了結構,請使用--parseInternal
。
如果要同時包括內部和依賴項,則使用兩個標誌
swag init --parseDependency --parseInternal
該項目的靈感來自Yvasiyarov/Swagger,但我們簡化了用法並增加了支持各種網絡框架。 Gopher圖像源是Tenntenn/Gopher-stickers。它具有Creative Commons許可。
由於所有貢獻的人,該項目的存在。 [貢獻]。
感謝我們所有的支持者! [成為支持者]
通過成為贊助商來支持這個項目。您的徽標將在此處顯示您網站的鏈接。 [成為贊助商]