基于golang的swagger
Swagger 相关的工具集会根据 OpenAPI 规范去生成各式各类的与接口相关联的内容,常见的流程是编写注解 =》调用生成库-》生成标准描述文件 =》生成/导入到对应的 Swagger 工具。
github: swaggo/swag
一般步骤:
1.按照swagger要求给接口代码添加声明式注释(https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html)
整体api说明:
| annotation | description | example |
|---|---|---|
| title | Required. The title of the application. | // @title Swagger Example API |
| version | Required. Provides the version of the application API. | // @version 1.0 |
| description | A short description of the application. | // @description This is a sample server celler server. |
| termsOfService | The Terms of Service for the API. | // @termsOfService http://swagger.io/terms/ |
| contact.name | The contact information for the exposed API. | // @contact.name API Support |
| contact.url | The URL pointing to the contact information. MUST be in the format of a URL. | // @contact.url http://www.swagger.io/support |
| contact.email | The email address of the contact person/organization. MUST be in the format of an email address. | // @contact.email support@swagger.io |
| license.name | Required. The license name used for the API. | // @license.name Apache 2.0 |
| license.url | A URL to the license used for the API. MUST be in the format of a URL. | // @license.url http://www.apache.org/licenses/LICENSE-2.0.html |
| host | The host (name or ip) serving the API. | // @host localhost:8080 |
| BasePath | The base path on which the API is served. | // @BasePath /api/v1 |
Security
| annotation | description | parameters | example |
|---|---|---|---|
| securitydefinitions.basic | Basic auth. | // @securityDefinitions.basic BasicAuth | |
| securitydefinitions.apikey | API key auth. | in, name | // @securityDefinitions.apikey ApiKeyAuth |
| securitydefinitions.oauth2.application | OAuth2 application auth. | tokenUrl, scope | // @securitydefinitions.oauth2.application OAuth2Application |
| securitydefinitions.oauth2.implicit | OAuth2 implicit auth. | authorizationUrl, scope | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
| securitydefinitions.oauth2.password | OAuth2 password auth. | tokenUrl, scope | // @securitydefinitions.oauth2.password OAuth2Password |
| securitydefinitions.oauth2.accessCode | OAuth2 access code auth. | tokenUrl, authorizationUrl, scope | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
| parameters annotation | example |
|---|---|
| in | // @in header |
| name | // @name Authorization |
| tokenUrl | // @tokenUrl https://example.com/oauth/token |
| authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
| scope.hoge | // @scope.write Grants write access |
Example
具体的API说明:
| annotation | description |
|---|---|
| description | A verbose explanation of the operation behavior. |
| id | A unique string used to identify the operation. Must be unique among all API operations. |
| tags | A list of tags to each API operation that separated by commas. |
| summary | A short summary of what the operation does. |
| accept | A list of MIME types the APIs can consume. Value MUST be as described under Mime Types. |
| produce | A list of MIME types the APIs can produce. Value MUST be as described under Mime Types. |
| param | Parameters that separated by spaces. param name,param type,data type,is mandatory?,comment attribute(optional) |
| security | Security to each API operation. |
| success | Success response that separated by spaces. return code,{param type},data type,comment |
| failure | Failure response that separated by spaces. return code,{param type},data type,comment |
| router | Failure response that separated by spaces. path,[httpMethod] |
Example
Limitation
- Not supported for cross-package models. Only search in project root folder. See #39
Mime Types
| Mime Type | annotation |
|---|---|
| application/json | application/json, json |
| text/xml | text/xml, xml |
| text/plain | text/plain, plain |
| html | text/html, html |
| multipart/form-data | multipart/form-data, mpfd |
| application/x-www-form-urlencoded | application/x-www-form-urlencoded, x-www-form-urlencoded |
| application/vnd.api+json | application/vnd.api+json, json-api |
| application/x-json-stream | application/x-json-stream, json-stream |
| application/octet-stream | application/octet-stream, octet-stream |
| image/png | image/png, png |
| image/jpeg | image/jpeg, jpeg |
| image/gif | image/gif, gif |
Security
General API info.
// @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
Each API operation.
// @Security ApiKeyAuth
Make it AND condition
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
Param Type
- object (struct)
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- array
Data Type
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- user defined struct
Attribute
// @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" mininum(1) maxinum(10)
// @Param default query string false "string default" default(A)
Available
| Field Name | Type | Description |
|---|---|---|
| default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined type for this parameter. |
| maximum | number |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. |
| minimum | number |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. |
| maxLength | integer |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. |
| minLength | integer |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. |
| enums | [*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. |
Future
| Field Name | Type | Description |
|---|---|---|
| format | string |
The extending format for the previously mentioned type. See Data Type Formats for further details. |
| multipleOf | number |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
| pattern | string |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. |
| maxItems | integer |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. |
| minItems | integer |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. |
| uniqueItems | boolean |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. |
| collectionFormat | string |
Determines the format of the array if type array is used. Possible values are:
Default value is |
TIPS
User defined structure with an array type
// @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"`
}
Use multiple path params
/// ...
// @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]
Example value of struct
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"`
}
2.使用swag工具扫描代码自动生成api接口文档数据(docs/)
3.使用gin-swagger渲染在线接口文档页面
[安装]
$ go get -u github.com/swaggo/swag/cmd/swag
$ go get -u github.com/swaggo/gin-swagger
$ go get -u github.com/swaggo/files $ go get -u github.com/alecthomas/template
验证是否安装成功
swag -v
swag version v1.8.1
[添加注释]
1.在main主入口文件添加项目相关介绍信息
package main // @title 这里写标题
// @version 1.0
// @description 这里写描述信息
// @termsOfService http://swagger.io/terms/ // @contact.name 这里写联系人信息
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io // @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host 这里写接口服务的host
// @BasePath 这里写base path
func main() {
r := gin.New() // liwenzhou.com ... r.Run()
}
2.在代码中处理请求的接口函数添加注释
// GetPostListHandler2 升级版帖子列表接口
// @Summary 升级版帖子列表接口
// @Description 可按社区按时间或分数排序查询帖子列表接口
// @Tags 帖子相关接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer 用户令牌"
// @Param object query models.ParamPostList false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
// @Router /posts2 [get]
func GetPostListHandler2(c *gin.Context) {
// GET请求参数(query string):/api/v1/posts2?page=1&size=10&order=time
// 初始化结构体时指定初始参数
p := &models.ParamPostList{
Page: 1,
Size: 10,
Order: models.OrderTime,
} if err := c.ShouldBindQuery(p); err != nil {
zap.L().Error("GetPostListHandler2 with invalid params", zap.Error(err))
ResponseError(c, CodeInvalidParam)
return
}
data, err := logic.GetPostListNew(p)
// 获取数据
if err != nil {
zap.L().Error("logic.GetPostList() failed", zap.Error(err))
ResponseError(c, CodeServerBusy)
return
}
ResponseSuccess(c, data)
// 返回响应
}
// bluebell/models/params.go // ParamPostList 获取帖子列表query string参数
type ParamPostList struct {
CommunityID int64 `json:"community_id" form:"community_id"` // 可以为空
Page int64 `json:"page" form:"page" example:"1"` // 页码
Size int64 `json:"size" form:"size" example:"10"` // 每页数据量
Order string `json:"order" form:"order" example:"score"` // 排序依据
}
// bluebell/controller/docs_models.go // _ResponsePostList 帖子列表接口响应数据
type _ResponsePostList struct {
Code ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data []*models.ApiPostDetail `json:"data"` // 数据
}
注解部分说明:
注解 描述
@Summary 摘要
@Produce API 可以产生的 MIME 类型的列表,MIME 类型你可以简单的理解为响应类型,例如:json、xml、html 等等
@Param 参数格式,从左到右分别为:参数名、入参类型、数据类型、是否必填、注释
@Success 响应成功,从左到右分别为:状态码、参数类型、数据类型、注释
@Failure 响应失败,从左到右分别为:状态码、参数类型、数据类型、注释
@Router 路由,从左到右分别为:路由地址,HTTP 方法
2.4.4.1 API
我们切换到项目目录下的 internal/routers/api/v1 目录,打开 tag.go 文件,写入如下注解:
// @Summary 获取多个标签
// @Produce json
// @Param name query string false "标签名称" maxlength(100)
// @Param state query int false "状态" Enums(0, 1) default(1)
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
// @Success 200 {object} model.Tag "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/tags [get]
func (t Tag) List(c *gin.Context) {} // @Summary 新增标签
// @Produce json
// @Param name body string true "标签名称" minlength(3) maxlength(100)
// @Param state body int false "状态" Enums(0, 1) default(1)
// @Param created_by body string true "创建者" minlength(3) maxlength(100)
// @Success 200 {object} model.Tag "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/tags [post]
func (t Tag) Create(c *gin.Context) {} // @Summary 更新标签
// @Produce json
// @Param id path int true "标签 ID"
// @Param name body string false "标签名称" minlength(3) maxlength(100)
// @Param state body int false "状态" Enums(0, 1) default(1)
// @Param modified_by body string true "修改者" minlength(3) maxlength(100)
// @Success 200 {array} model.Tag "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/tags/{id} [put]
func (t Tag) Update(c *gin.Context) {} // @Summary 删除标签
// @Produce json
// @Param id path int true "标签 ID"
// @Success 200 {string} string "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/tags/{id} [delete]
func (t Tag) Delete(c *gin.Context) {}
[生成接口文档数据]
swag init
--generallinfo value 指定go项目入口文件, 默认是main.go
--swagger value 配置输出的文件的目录 默认 ./docs/swagger
# 指定入口文件与输出路径
swag init -g cmd/app/main.go -o ./docs
./docs
├── docs.go
├── swagger.json
└── swagger.yaml
[渲染文档]
import (
// liwenzhou.com ... _ "bluebell/docs" // 千万不要忘了导入把你上一步生成的docs gs "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles" "github.com/gin-gonic/gin"
) 注册路由:
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) 把你的项目程序运行起来,打开浏览器访问 http://localhost:8080/swagger/index.html 就能看到Swagger 2.0 Api文档了。 gin-swagger 同时还提供了 DisablingWrapHandler 函数,方便我们通过设置某些环境变量来禁用Swagger。例如:
r.GET("/swagger/*any", gs.DisablingWrapHandler(swaggerFiles.Handler, "NAME_OF_ENV_VARIABLE")) 此时如果将环境变量 NAME_OF_ENV_VARIABLE设置为任意值,则 /swagger/*any 将返回404响应,就像未指定路由时一样。
常见错误:
1.
Failed to load API definition
原因:
_ "bluebell/docs" // 千万不要忘了导入把你上一步生成的docs 缺少这个初始化并注册操作
问题见:https://github.com/swaggo/swag/issues/830
参考文档:
- https://www.cnblogs.com/niuben/p/15634136.html
基于golang的swagger的更多相关文章
- Gravitational Teleport 是一个先进的 SSH 服务器,基于 Golang SSH 构建,完全兼容 OpenSSH
Gravitational Teleport 是一个先进的 SSH 服务器,可通过 SSH 或者 HTTPS 远程访问 Linux 服务器.其目的是为了替代 sshd.Teleport 可以轻松让团队 ...
- 马蜂窝搜索基于 Golang 并发代理的一次架构升级
搜索业务是马蜂窝流量分发的重要入口.很多用户在使用马蜂窝时,都会有目的性地主动搜索与自己旅行需求相关的各种信息,衣食住行,事无巨细,从而做出最符合需求的旅行决策. 因此在马蜂窝,搜索业务交互的下游模块 ...
- 基于Golang设计一套微服务架构[转]
article- @嘟嘟噜- May/26/2018 18:35:30 如何基于Golang设计一套微服务架构 微服务(Microservices),这个近几年我们经常听到.那么现在市面上的的微服 ...
- flipt 一个基于golang 的特性工具开发类库
以前介绍过一个Flagr 的基于golang 的特性功能开发类库(技术雷达推荐),今天看到一个类似也很不错的方案flipt 参考架构 包含的特性 快速,使用golang 编写,同时进行了性能优化 运行 ...
- 花椒直播基于golang的中台技术实践
https://github.com/gopherchina/conference/blob/master/2019/2.7%20花椒直播基于golang的中台技术实践%20-%20周洋.pdf 花椒 ...
- Go语言入门篇-gRPC基于golang & java简单实现
一.什么是RPC 1.简介: RPC:Remote Procedure Call,远程过程调用.简单来说就是两个进程之间的数据交互. 正常服务端的接口服务是提供给用户端(在Web开发中就是浏览器)或者 ...
- 基于 Golang 完整获取百度地图POI数据的方案
百度地图为web开发者提供了基于HTTP/HTTPS协议的丰富接口,其中包括地点检索服务,web开发者通过此接口可以检索区域内的POI数据.百度地图处于数据保护对接口做了限制,每次访问服务,最多只能检 ...
- 基于golang分布式爬虫系统的架构体系v1.0
基于golang分布式爬虫系统的架构体系v1.0 一.什么是分布式系统 分布式系统是一个硬件或软件组件分布在不同的网络计算机上,彼此之间仅仅通过消息传递进行通信和协调的系统.简单来说就是一群独立计算机 ...
- gofs使用教程-基于golang的开源跨平台文件同步工具
概述 gofs是基于golang开发的一款开箱即用的跨平台文件同步工具,开源地址如下:https://github.com/no-src/gofs,欢迎点个Star或者提交Issue和PR,共同进步! ...
- Fastflow——基于golang的轻量级工作流框架
Fastflow 是什么?用一句话来定义它:一个 基于golang协程.支持水平扩容的分布式高性能工作流框架. 它具有以下特点: 易用性:工作流模型基于 DAG 来定义,同时还提供开箱即用的 API, ...
随机推荐
- kubernetes重新初始化“[ERROR DirAvailable--var-lib-etcd]”
[root@master01 ~]# kubeadm init --config /root/kubeadm-config.yaml --upload-certs [init] Using Kuber ...
- Linux下Shell脚本实现统一管理服务启停重启
公司今年开始了大批量的裁员,人心惶惶,所以强迫自己学习点新知识,刚好领导给找了个事情,让写个脚本实现一键启停Linux服务器上的服务,于是开始研究这个怎么搞. 最开始的时候,有点想当然了,觉得一键启停 ...
- SEO – Schema and JSON-LD
大纲介绍 Schema 是 Google, Microsoft, Yahoo 联合成立的, 目的是统一网页的表示方式, 这样搜素引擎会比较方便显示内容. 它虽然不算那种 w3c 独立的组织. 但其它的 ...
- SQL Server 中的 NUL 设备/NIL设备
SQL Server 中的 NUL 设备/NIL设备 在 SQL Server 中,有一个特殊的设备叫做 NUL(注意,不是 NULL),它类似于文件系统中的"黑洞".NUL 设备 ...
- 推荐3款卓越的 .NET 开源搜索组件库
前言 最近有不少同学提问:.NET有哪些开源的搜索组件库可以推荐的吗?,今天大姚给大家推荐3款卓越的 .NET 开源搜索组件库,希望可以帮助到有需要的同学. Elasticsearch .NET El ...
- Codes 开源研发项目管理平台——创新的敏捷测试解决方案
前言 Codes 是国内首款重新定义 SaaS 模式的开源项目管理平台,支持云端认证.本地部署.全部功能开放,并且对 30 人以下团队免费.它通过整合迭代.看板.度量和自动化等功能,简化测试协同工作, ...
- 如何创建免费版本的ABP分离模块?
如何创建免费版本的ABP分离模块? 由于ABP最近官方大改革,我们打开ABP.IO 官方会发现通过Cli创建模板的时候不能创建Trered类型的了 就是创建一个分层的解决方案,其中Web和Http A ...
- Blazor与IdentityServer4的集成
本文合并整理自 CSDN博主「65号腕」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明. Blazor与IdentityServer4的集成(一) IdentityS ...
- 高通ramdump
背景 高通平台下提供了一个工具,专门用来抓取内核死机以后的dump信息.如果只是非系统层面的crash(例如底层应用,安卓程序),则不能抓取dump信息. 在阅读一些文档的时候知道有这个功能,但是一直 ...
- 好文分享 | 记一次Oracle12c数据库SQL短暂缓慢问题分析
本文为墨天轮社区作者 张sir 原创作品,记录了日常运维Oracle数据库过程中遇到的一个慢SQL问题的解决.优化过程,文章内容全面具体.分析到位,且含有经验总结,分享给各位. 问题现象 这次出问题的 ...