【swaggo】swaggo使用详解
- 游戏开发
- 2025-08-21 01:45:02

一、swagger简介
swagger是一套基于OpenAPI规范构建的开源工具,使用RestApi。swagger-ui 呈现出来的是一份可交互式的API文档,可以直接在文档页面尝试API的调用。 gin-swagger 是基于注释生成 API 文档,项目地址: github /swaggo/swag。
二、安装 2.1.安装swag //go版本1.16之前使用该命令 go get -u github /swaggo/swag/cmd/swag //go版本1.16版本以及之后的版本使用该命令 go install github /swaggo/swag/cmd/swag@latest 2.2.swag 命令 swag -h NAME: swag.exe - Automatically generate RESTful API documentation with Swagger 2.0 for Go. USAGE: swag.exe [global options] command [command options] [arguments...] VERSION: v1.8.8 COMMANDS: init, i 创建docs.go fmt, f 格式化swag注释 help, h 展示命令列表或者查看命令帮助 GLOBAL OPTIONS: --help, -h show help (default: false) --version, -v print the version (default: false) swag init -h NAME: swag.exe init - Create docs.go USAGE: swag.exe init [command options] [arguments...] OPTIONS: --quiet, -q 禁用日志,默认 false --generalInfo value, -g value 写入通用 API信息的 go文件路径,默认 main.go --dir value, -d value 需要解析文件的路径,用逗号分隔,通用信息路径必须在第一个,默认是"./" --exclude value 搜索时排除的路径和文件,用逗号分隔 --propertyStrategy value, -p value 属性命名策略,有蛇式、驼峰式,帕斯卡式,默认驼峰式 --output value, -o value 生成文件的输出路径(swagger.json, swagger.yaml and docs.go),默认"./docs" --outputTypes value, --ot value 生成文件的输出类型(docs.go、swagger.json、swagger.yaml),如go、json、yaml 默认"go,json,yaml" --parseVendor 是否解析 vendor 文件夹下的过文件,默认 false --parseDependency, --pd 是否解析依赖路径下的 go文件,默认 false --markdownFiles value, --md value 指定包含 markdown 文件的路径,可解析为API说明,默认禁用 --codeExampleFiles value, --cef value 指定包含用于 x-codeSamples 扩展的代码示例文件的文件夹,默认禁用 --parseInternal 是否解析内部包中的 go文件,默认 false --generatedTime 是否在 docs.go 顶部生成时间戳,默认 false --parseDepth value 解析依赖深度,默认100 --requiredByDefault 是否设置所有文件需要验证,默认false --instanceName value 设置swagger文档实例名,可选。 --overridesFile value 全局类型重写文件,默认 ".swaggo" --parseGoList 是否通过 'go list' 解析,默认 true --tags value, -t value 以逗号分隔的标记列表,用于筛选生成文档的API。如果标记前缀为“!”,则具有该标记的API将被排除 --help, -h 帮助 三、使用声明:使用方法大部分是参考swaggo git仓库的说明文档,仓库地址: github /swaggo/swag
3.1.与Gin集成 使用 swag init生成 Swagger 2.0文件后,导入如下几个包 : import "github /swaggo/gin-swagger" // gin-swagger middleware import "github /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:// .swagger.io/support // @contact.email support@swagger.io // @license.name Apache 2.0 // @license.url http:// .apache.org/licenses/LICENSE-2.0.html // @host localhost:8080 // @BasePath /api/v1 // @securityDefinitions.basic BasicAuth 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变量,使用该变量可以通过编码的方式设置标题、描述、版本、主机和基础路径。使用Gin的示例:
package main import ( "github /gin-gonic/gin" "github /swaggo/files" "github /swaggo/gin-swagger" "./docs" // docs is generated by Swag CLI, you have to import it. ) // @contact.name API Support // @contact.url http:// .swagger.io/support // @contact.email support@swagger.io // @license.name Apache 2.0 // @license.url http:// .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 /gin-gonic/gin" "github /swaggo/swag/example/celler/httputil" "github /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 运行程序,然后浏览器访问http://localhost:8080/swagger/index.html 。将看到Swagger 2.0 Api文档,如下所示: 3.2.格式化工具在使用的时候发现一个问题, 使用格式化工具对通用API信息进行格式化的时候,会使用制表符对齐,但是 swag init 解析的时候解析不出来通用API注释 可以针对Swag的注释自动格式化,就像go fmt命令一样。 用法:
swag fmt排除路径:
swag fmt -d ./ --exclude ./internal使用swag fmt时,为了确保格式正确,需要保证为函数提供文档注释。这是由于swag fmt只允许在标准文档注释之后使用tabs缩进。 例如:
// 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) { 3.3.通用API注释 注释说明示例title必填。程序标题// @title Swagger Example APIversion必填。 程序API版本// @version 1.0description程序简短描述// @description This is a sample server celler server.tag.name标签名// @tag.name This is the name of the tagtag.description标签描述// @tag.description Cool Descriptiontag.docs.url标签的外部文档URL// @tag.docs.url example tag.docs.description标签的外部文档说明// @tag.docs.description Best example documentationtermsOfServiceAPI服务条款// @termsOfService http://swagger.io/terms/contact.name公开的API联系信息// @contact.name API Supportcontact.url联系信息URL。必须采用网址格式// @contact.url http:// .swagger.io/supportcontact.email联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。// @contact.email support@swagger.iolicense.name必填。 用于API的许可证名称// @license.name Apache 2.0license.url用于API的许可证URL。必须采用网址格式// @license.url http:// .apache.org/licenses/LICENSE-2.0.htmlhost运行API的主机(主机名或者IP地址)// @host localhost:8080BasePath运行API的基本路径// @BasePath /api/v1acceptAPI可以使用的MIME类型列表。注意,Accept仅影响具有body的请求,例如POST、PUT和PATCH。值必须是Mime类型中的一种// @accept jsonproduceAPI可以生成的MIME类型列表。值必须是Mime类型中的一种// @produce jsonquery.collection.format请求URI query里数组参数的默认格式:csv,multi,pipes,tsv,ssv。 如果未设置,则默认为csv// @query.collection.format multischemes用空格分隔的请求的传输协议// @schemes http httpsx-name扩展的键必须以x-开头,并且只能使用json值// @x-example-key {“key”: “value”} 3.3.1.使用Markdown描述如果文档中的短字符串不足以完整表达,或者需要展示图片,代码示例等类似的内容,则可能需要使用Markdown描述。要使用Markdown描述,请使用一下注释。
注释说明示例title必填。程序标题// @title Swagger Example APIversion必填。 程序API版本// @version 1.0description.markdown程序的简短描述。从api.md文件解析。这是@description的替代用法// @description.markdown No value needed, this parses the description from api.mdtag.name标签名// @tag.name This is the name of the tagtag.description.markdown标签的说明。这是tag.description的替代用法。 该描述将从名为tagname.md的文件中读取// @tag.description.markdown 3.4.接口API操作注释 注释说明description操作行为的详细说明description.markdown应用程序的简短描述。会从文件中读取描述。例如@description.markdown details将加载details.mdid用于标识API操作的唯一字符串。在所有API操作中必须是唯一的tagsAPI所属的标签列表,用逗号分隔summary操作的简短摘要acceptAPI可以使用的MIME类型列表。注意,Accept仅影响具有body的请求,例如POST、PUT和PATCH。值必须是Mime类型中的一种produceAPI可以生成的MIME类型列表.。值必须是Mime类型中的一种param以空格分隔的参数。 参数名, 参数类型, 数据类型, 是否强制, "注释", 属性(可选)securityAPI操作的安全性success以空格分隔的成功响应。 状态码,{参数类型},数据类型,"注释" , 注意这里的参数类型和 @param的参数类型不同,这里和数据类型有点相似,可以取值 {string}, {array}, {object}等failure以空格分隔的失败响应。 状态码,{参数类型},数据类型,"注释" , 注意这里的参数类型和 @param的参数类型不同,这里和数据类型有点相似,可以取值 {string}, {array}, {object}等response和 success 、failure用法相同header以空格分隔的头字段。 状态码,{参数类型},数据类型,"注释" , 注意这里的参数类型和 @param的参数类型不同,这里和数据类型有点相似,可以取值 {string}, {array}, {object}等router以空格分隔的路径定义。 path,[httpMethod]x-name扩字段必须以x-开头,并且只能接受json值x-codeSample可选的Markdown用法。将“file”作为参数。然后会在给定文件夹中搜索类似summary的文件deprecated标记API为废弃状态 3.5.Mime类型swag 接受所有格式正确的MIME类型,即匹配 /。 另外,swag也会接收一些如下所示的别名:
别名MIME 类型jsonapplication/jsonxmltext/xmlplaintext/plainhtmltext/htmlmpfdmultipart/form-datax- -form-urlencodedapplication/x- -form-urlencodedjson-apiapplication/vnd.api+jsonjson-streamapplication/x-json-streamoctet-streamapplication/octet-streampngimage/pngjpegimage/jpeggifimage/gif 3.6.参数类型 querypathheaderbodyformData 3.7.数据类型 string (string)integer (int, uint, uint32, uint64)number (float32)boolean (bool)user defined struct 3.8.安全性 注释说明参数例子securitydefinitions.basicBasic auth.// @securityDefinitions.basic BasicAuthsecuritydefinitions.apikeyAPI key auth.in, name, description// @securityDefinitions.apikey ApiKeyAuthsecuritydefinitions.oauth2.applicationOAuth2 application auth.tokenUrl, scope, description// @securitydefinitions.oauth2.application OAuth2Applicationsecuritydefinitions.oauth2.implicitOAuth2 implicit auth.authorizationUrl, scope, description// @securitydefinitions.oauth2.implicit OAuth2Implicitsecuritydefinitions.oauth2.passwordOAuth2 password auth.tokenUrl, scope, description// @securitydefinitions.oauth2.password OAuth2Passwordsecuritydefinitions.oauth2.accessCodeOAuth2 access code auth.tokenUrl, authorizationUrl, scope, description// @securitydefinitions.oauth2.accessCode OAuth2AccessCode 参数注释示例in// @in headername// @name AuthorizationtokenUrl// @tokenUrl example /oauth/tokenauthorizationurl// @authorizationurl example /oauth/authorizescope.hoge// @scope.write Grants write accessdescription// @description OAuth protects our entity endpoints 3.9.属性 // @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"` } 3.9.1.可用属性 字段名类型说明validatestring参数验证。可选值有:required,optionaldefault*如果未提供指定参数,服务器将使用此参数默认值。例如,使用"count"控制每页结果的数量,如果客户端未在请求中传入此参数,则可以设置参数默认值为100。(注意:默认参数对必填参数无效。)请参阅 tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2.与JSON模式不同,该值必须符合为该参数定义的type。maximumnumberSee tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.minimumnumberSee tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.multipleOfnumberSee tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.maxLengthintegerSee tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.minLengthintegerSee tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.enums[*]See tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1.formatstring上面提到的类型的扩展格式。有关更多详细信息,请参见数据类型格式collectionFormatstringDetermines the format of the array if type array is used. Possible values are: csv - comma separated values foo,bar. ssv - space separated values foo bar. tsv - tab separated values foo\tbar. pipes - pipe separated values foo|bar. multi - corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in “query” or “formData”. Default value is csv.example*Declares the example for the parameter valueextensionsstringAdd extension to parameters. 3.10.示例 3.10.1.多行的描述可以在常规api描述或路由定义中添加跨越多行的描述,如下所示:
// @description This is the first line // @description This is the second line // @description And so forth. 3.10.2.用户自定义的具有数组类型的结构 // @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"` } 3.10.3.函数作用域结构声明可以在函数体中声明请求响应结构体。You can declare your request response structs inside a function body。 必须遵循命名约定<包名>.<函数名>.<结构体名称>。
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 } } 3.10.4.响应对象中的模型组合 // 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" 3.10.5.在响应中增加头字段 // @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" 3.10.6.使用多路径参数 /// ... // @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] 3.10.7.添加多路径 /// ... // @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] 3.10.8.结构体的示例值 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"` } 3.10.9.body的SchemaExample // @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n) 3.10.10.结构体描述 // 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文档如下:
"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" } } } 3.10.11.使用swaggertype标签更改字段类型#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传递映射到swag,可以在任何地方使用一种类型代替另一种类型。默认情况下,如果当前目录中存在“.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" } 3.10.12.使用swaggerignore标签排除字段 type Account struct { ID string `json:"id"` Name string `json:"name"` Ignored int `swaggerignore:"true"` } 3.10.13.将扩展信息添加到结构字段 type Account struct { ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-" }生成的swagger文档如下:
"Account": { "type": "object", "properties": { "id": { "type": "string", "x-nullable": true, "x-abc": "def", "x-omitempty": false } } } 3.10.14.对展示的模型重命名 type Resp struct { Code int }//@name Response 3.10.15.如何使用安全性注释通用API信息
// @securityDefinitions.basic BasicAuth // @securitydefinitions.oauth2.application OAuth2Application // @tokenUrl example /oauth/token // @scope.write Grants write access // @scope.admin Grants read and write access to administrative information单个API操作
// @Security ApiKeyAuth使用AND条件
// @Security ApiKeyAuth // @Security OAuth2Application[write, admin]使用OR条件
// @Security ApiKeyAuth || firebase // @Security OAuth2Application[write, admin] || APIKeyAuth 3.10.16.添加枚举项的说明 type Example struct { // Sort order: // * asc - Ascending, from A to Z. // * desc - Descending, from Z to A. Order string `enums:"asc,desc"` } 3.10.17.仅生成特定的文档文件类型默认情况下,swag命令使用如下三种不同的文件生成Swagger规范:
docs.goswagger.jsonswagger.yaml如果要限制应生成的一组文件类型,可以使用--outputTypes(-ot)标志。默认值为go,json,yaml-输出类型用逗号分隔。要将输出限制为go和yaml文件,可以编写go,yaml。使用完整的命令swag init--outputTypes go,yaml。
【swaggo】swaggo使用详解由讯客互联游戏开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“【swaggo】swaggo使用详解”
上一篇
Vue-npm批量升级依赖包
下一篇
PS1文件执行