?英语∙简体中文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许可。
由于所有贡献的人,该项目的存在。 [贡献]。
感谢我们所有的支持者! [成为支持者]
通过成为赞助商来支持这个项目。您的徽标将在此处显示您网站的链接。 [成为赞助商]