[关闭]
@daduizhang 2019-02-27T06:37:28.000000Z 字数 7351 阅读 1655

Swagger相关内容

swagger go go-swagger


什么是swagger?

Swagger是一个简单但功能强大的API表达工具。它具有地球上最大的API工具生态系统,数以千计的开发人员,使用几乎所有的现代编程语言,都在支持和使用Swagger。使用Swagger生成API,我们可以得到交互式文档,自动生成代码的SDK以及API的发现特性等。

swagger文档长啥样?

  1. swagger: "2.0"
  2. info:
  3. version: 1.0.0
  4. title: Simple API
  5. description: A simple API to learn how to write OpenAPI Specification
  6. schemes:
  7. - https
  8. host: simple.api
  9. basePath: /openapi101
  10. paths: {}

go-swagger的安装方式

安装有多种方式, 介绍两个稍微常用的安装方式:

  1. # brew
  2. brew tap go-swagger/go-swagger
  3. brew install go-swagger
  4. # go get
  5. go get -u github.com/go-swagger/go-swagger/cmd/swagger

如何使用go-swagger?

下面我们讲解一下如何使用go-swagger,在使用之前你或许需要了解一下openAPI是做什么的,我们现在所做的认为你对openAPI有所了解。

因为我们所做的是依靠源码生成我们要的swagger文档,所以你现在要记住一个这样的命令:

  1. # 根源源码生成一个swagger文档,他的类型可以是json或者是yaml,根据你的后缀名
  2. swagger generate spec -o ./swagger.json/yaml
  3. # 测试这个swagger文档是否有效
  4. swagger validate ./swagger.json/yaml
  5. 如出现这样一段话,则表示你生成的yamljson文件没有问题:
  6. The swagger spec at "swagger.json/yaml" is valid against swagger specification 2.0

现在我们知道了这样的两个命令,我们就要知道如何才能生成一个合格的swagger文档呢,这时候我们就需要了解一下在源码中如何写注释,从而可以获取这些文档。

理解go-swagger中的注释

我们来看一下都有哪些形态的注释:

  1. Swagger:meta
  2. Swagger:route
  3. Swagger:params
  4. Swagger:operation
  5. Swagger:response
  6. Swagger:model
  7. Swagger:allOf
  8. Swagger:strfmt
  9. Swagger:discriminated
  10. Swagger:ignore

接下来我们会一一讲解这些具体怎么做:

Swagger:meta

这是你应该添加到项目中的第一个注释。它被用来描述你的项目名称,描述,联系电子邮件,网站,许可证等等信息。

  1. // Package classification Petstore API.
  2. //
  3. // the purpose of this application is to provide an application
  4. // that is using plain go code to define an API
  5. //
  6. // This should demonstrate all the possible comment annotations
  7. // that are available to turn go code into a fully compliant swagger 2.0 spec
  8. //
  9. // Terms Of Service:
  10. //
  11. // there are no TOS at this moment, use at your own risk we take no responsibility
  12. //
  13. // Schemes: http, https
  14. // Host: localhost
  15. // BasePath: /v2
  16. // Version: 0.0.1
  17. // License: MIT http://opensource.org/licenses/MIT
  18. // Contact: John Doe<john.doe@example.com> http://john.doe.com
  19. //
  20. // Consumes:
  21. // - application/json
  22. // - application/xml
  23. //
  24. // Produces:
  25. // - application/json
  26. // - application/xml
  27. //
  28. // Security:
  29. // - api_key:
  30. //
  31. // SecurityDefinitions:
  32. // api_key:
  33. // type: apiKey
  34. // name: KEY
  35. // in: header
  36. // oauth2:
  37. // type: oauth2
  38. // authorizationUrl: /oauth2/auth
  39. // tokenUrl: /oauth2/token
  40. // in: header
  41. // scopes:
  42. // bar: foo
  43. // flow: accessCode
  44. //
  45. // Extensions:
  46. // x-meta-value: value
  47. // x-meta-array:
  48. // - value1
  49. // - value2
  50. // x-meta-array-obj:
  51. // - name: obj
  52. // value: field
  53. //
  54. // swagger:meta
  55. package classification

我们来讲一下这里面的一些参数的设定:

参数 介绍
Terms Of Service 描述API的一些基本信息,和一些请求的基本信息
Consumes API从客户端接收的内容的默认(全局)mime类型值列表,每行一个。
Produces API发送给客户端的内容的默认(全局)mime类型值列表,每行一个。
Schemes http、https
Version 版本号
Host 主机的地址
BasePath API的基础路径
License 许可证明
Contact 联系人等信息
Security api-key
SecurityDefinitions 一些授权的信息,比如JWT
Extensions 一些扩展行的信息

当你执行生成文档的命令时,会生成一个yaml/json文件,你应该可以看到这样的信息:

  1. ---
  2. swagger: '2.0'
  3. consumes:
  4. - application/json
  5. - application/xml
  6. produces:
  7. - application/json
  8. - application/xml
  9. schemes:
  10. - http
  11. - https
  12. info:
  13. description: "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec"
  14. title: 'Petstore API.'
  15. termsOfService: 'there are no TOS at this moment, use at your own risk we take no responsibility'
  16. contact: {name: 'John Doe', url: 'http://john.doe.com', email: john.doe@example.com}
  17. license: {name: MIT, url: 'http://opensource.org/licenses/MIT'}
  18. version: 0.0.1
  19. host: localhost
  20. basePath: /v2
  21. x-meta-value: value
  22. x-meta-array:
  23. - value1
  24. - value2
  25. x-meta-array-obj:
  26. - name: obj
  27. value: field

Swagger:route

有两种方式两个注释你的路由,swagger:operation 和swagger:route。两者看起来都很相似,那么主要区别是什么?
把 swagger:route 看作简单 API 的短注释,它适用于没有输入参数(路径/查询参数)的 API 。那些(带有参数)的例子是 /repos/{owner} , /user/{id} 或者 /users/search?name=ribice。

  1. // ServeAPI serves the API for this record store
  2. func TestSwagger(c *gin.Context) {
  3. // swagger:route GET /pets PetsUsers listPets
  4. //
  5. // Lists pets filtered by some parameters.
  6. //
  7. // This will show all available pets by default.
  8. // You can get the pets that are out of stock
  9. //
  10. // Responses:
  11. // default: genericError
  12. // 200: someResponse
  13. // 400: validationError

我们来解释一下swagger:route 后面的参数都是干什么的:

参数 介绍
GET get请求
/pets 匹配的url地址
PetsUsers 路由所在的空间分割标签
listPets 用于此端点的请求
Lists pets.. 摘要(标题)。对于swager:route注释,在第一个句号(.)前面的是标题。如果没有句号,就会没有标题并且这些文字会被用于描述。
This will... 描述。对于swager:route类型注释,在第一个句号(.)后面的是描述。
responses 这个端点的响应
default 默认返回的错误,包含genericError(用 swagger:response 注释的模型)
200 一个(成功的)响应HTTP状态 200,包含 repoResp(用 swagger:response 注释的模型)
400 此端点的错误响应,包含 validationError(用 swagger:response 注释的模型)

当你执行生成文档的命令时,会生成一个yaml/json文件,你应该可以看到这样的信息:

  1. ---
  2. paths:
  3. "/pets":
  4. get:
  5. operationId: listPets
  6. summary: Lists pets filtered by some parameters.
  7. description: "This will show all available pets by default.\nYou can get the pets that are out of stock"
  8. tags:
  9. - PetsUsers
  10. responses:
  11. default:
  12. $ref: "#/responses/genericError"
  13. 200:
  14. $ref: "#/responses/someResponse"
  15. 422:
  16. $ref: "#/responses/validationError"

Swagger:operation

使用 Swagger:operation 可以让你使用所有OpenAPI规范,你可以描述你的复杂的端点, 如果你对细节感兴趣,你可以阅读openAPI的规范文档。

  1. // ServeAPI serves the API for this record store
  2. func TestSwagger(c *gin.Context) {
  3. // swagger:operation GET /repo/{author} repos repoList
  4. // ---
  5. // summary: List the repositories owned by the given author.
  6. // description: If author length is between 6 and 8, Error Not Found (404) will be returned.
  7. // parameters:
  8. // - name: author
  9. // in: path
  10. // description: username of author
  11. // type: string
  12. // required: true
  13. // responses:
  14. // "200":
  15. // "$ref": "#/responses/reposResp"
  16. // "404":
  17. // "$ref": "#/responses/notFound"

我们可以看到这根我们平常写入的openAPI的文档格式一毛一样,我们来解释一下各个参数吧:

参数 介绍
GET get请求
/repo/{author} 匹配的url地址
repos 路由所在的空间分割标签
repoList 用于此端点的请求,这个不存在(没有定义),但参数是强制性的,所以你可以用任何东西来替换repoList(noReq,emptyReq等)
“---” 这个部分下面是YAML格式的swagger规范。确保您的缩进是一致的和正确的,否则将无法正确解析。注意,如果你在YAML中定义了标签,摘要,描述或操作标签,将覆盖上述常规swagger语法中的摘要,描述,标记或操作标签。

Swagger:parameters

生成的swagger规范中的参数:

  1. // swagger:parameters test_demo
  2. type BarSliceParam struct {
  3. // a BarSlice has bars which are strings
  4. //
  5. // min items: 3
  6. // max items: 10
  7. // unique: true
  8. // Required: true
  9. // in: query
  10. Name string `json:"name"`
  11. }

ps: 此结构的字段可以使用许多注释进行修饰。对于字段名称,它使用struct字段名称,它尊重json struct字段标记以自定义名称。
我们来解释一下swagger:parameters 后面的参数都是干什么的:

参数 介绍
test_demo operationID, go-swagger会以此来寻找你的关联的方法
a BarSlice... 这个就是你参数的描述
minLength 参数最短长度
maxLength 参数最大长度
in 参数放在什么位置,如:body,query,path
unique 参数是否是唯一的
Required 是否必传

当你执行生成文档的命令时,会生成一个yaml/json文件,你应该可以看到这样的信息:

  1. ---
  2. operations:
  3. "/":
  4. get:
  5. operationId: test_demo
  6. parameters:
  7. - name: name
  8. in: query
  9. maxLength: 10
  10. minLength: 3
  11. unique: true
  12. Required: true

Swagger:response

响应注释与参数注释非常相似。主要的区别在于,经常将响应包裹到更复杂的结构中。
一般的响应会是这样的:

  1. {
  2. "msg": "OK"
  3. "code":200, // Code containing HTTP status CODE
  4. "data":{} // Data containing actual response data
  5. }

要使用常规响应,像上面错误响应那样的,我们需要在代码中新建一个reponse.go这种类似的文件,下面的响应用于 OK 响应(不返回任何数据):

  1. // A ValidationError is an error that is used when the required input fails validation.
  2. // swagger:response validationError
  3. type ValidationError struct {
  4. // The error message
  5. // in: body
  6. Body struct {
  7. // The validation message
  8. //
  9. // Required: true
  10. Message string
  11. // An optional field name to which this validation applies
  12. FieldName string
  13. }
  14. }

或者是这样的形式:

  1. // 成功或失败返回的数据格式
  2. // swagger:response SwaggerResponse
  3. type SwaggerWapper struct {
  4. // The error message
  5. // in: body
  6. Body ResponseMessage
  7. }
  8. type ResponseMessage struct {
  9. // 返回的code码
  10. // Required: true
  11. Code int `json:"code"`
  12. Msg string `json:"msg"`
  13. Data interface{} `json:"data"`
  14. }

只是生成出来的效果不一样,第一个展现的json/yaml格式会被展开:

  1. ---
  2. responses:
  3. validationError:
  4. description: A ValidationError is an error that is used when the required input fails validation.
  5. schema:
  6. type: object
  7. description: The error message
  8. required:
  9. - Message
  10. properties:
  11. Message:
  12. type: string
  13. description: The validation message
  14. example: Expected type int
  15. FieldName:
  16. type: string
  17. description: an optional field name to which this validation applies

而第二种形式的则会被建华折叠起来,如这样:

  1. responses:
  2. SwaggerResponse:
  3. description: 成功或失败返回的数据格式
  4. schema:
  5. $ref: '#/definitions/ResponseMessage'
  6. definitions:
  7. ResponseMessage:
  8. properties:
  9. code:
  10. description: 返回的code
  11. type: integer
  12. data:
  13. type: object
  14. msg:
  15. type: string
  16. required:
  17. - code
  18. type: object

第二种形式更加通用,复用性很好,Swagger:response和Swagger:parameters的注释形式基本没差,就不讲解更多了。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注