当前位置:网站首页>Golang-based swagger super intimate and super detailed usage guide [there are many pits]
Golang-based swagger super intimate and super detailed usage guide [there are many pits]
2022-07-31 08:31:00 【asdfadafd】
Swagger 相关的工具集会根据 OpenAPI 规范去生成各式各类的与接口相关联的内容,常见的流程是编写注解 =》调用生成库-》生成标准描述文件 =》生成/导入到对应的 Swagger 工具.
安装
因此接下来第一步,我们要先安装 Go 对应的开源 Swagger 相关联的库,在项目 blog-service 根目录下执行安装命令,如下:
$ 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.6.5
此处有坑:go get命令分两步:第一步如同git clone拉取github上的依赖并下载,第二步就是会go install编译,这个swagger包比较特殊,go install编译会编译出可执行文件,然后放在GOBIN.因此GOBINThe directory selection must be selected in the readable and writable directory,If you put it in a read-only folder,会安装不了swagger的可执行文件的!!!会报错:access deniedInsufficient reminder permission
write comments
在完成了 Swagger After installation of the associated library,We need to target the project API Writing interface annotations,So that the subsequent generation can run correctly,Next we will use the following annotations:
注解 描述
@Summary 摘要
@Produce API 可以产生的 MIME 类型的列表,MIME Type you can simply understand as the response type,例如:json、xml、html 等等
@Param 参数格式,从左到右分别为:参数名、入参类型、数据类型、是否必填、注释
@Success 响应成功,从左到右分别为:状态码、参数类型、数据类型、注释
@Failure 响应失败,从左到右分别为:状态码、参数类型、数据类型、注释
@Router 路由,从左到右分别为:路由地址,HTTP 方法
2.4.4.1 API
We switch to the project directory internal/routers/api/v1 目录,打开 tag.go 文件,Write the following annotations:
// @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) {}
Here we only show the interface annotation writing of the tag module,Next, you should follow the meaning of the annotation and refer to the above interface annotation,Complete the writing of the article module interface annotations.
main注解
Then the interface method itself is annotated,that for this project,Can you write a note?,In case there are many items,how to know who it is?In fact can be identified,我们只要针对 main The method is written in the following annotation:
// @title 博客系统
// @version 1.0
// @description Go 语言编程之旅:一起用 Go 做项目
// @termsOfService https://github.com/go-programming-tour-book
func main() {
...
}
生成
After finished all the annotations to write,Let's go back to the project root directory,执行如下命令:
$ swag init
After executing the command,会发现在 docs 文件夹生成 docs.go、swagger.json、swagger.yaml 三个文件.
路由
The notes written,也通过 swag init 把 Swagger API All required files are generated,Then how can we access interface documentation?其实很简单,我们只需要在 routers You can initialize and register the corresponding route by default in,打开项目目录下的 internal/routers 目录中的 router.go 文件,新增代码如下:
import (
...
_ "github.com/go-programming-tour-book/blog-service/docs"
//_ 表示执行initWhen the function is called, the package is changed,You need to replace this with your own localdocs目录路径.这个路径是github上别人的docs,This is just for testing.
//It should be written like this:_ "swagger_demo/docs"
//上面的swagger_demoFor the project name,docs就是swag init自动生成的目录,用于存放 docs.go、swagger.json、swagger.yaml 三个文件.
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
func NewRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
...
return r
}
从表面上来看,主要做了两件事,分别是初始化 docs package and register one for swagger 的路由,而在初始化 docs 包后,其 swagger.json By default, it will point to the domain name under the domain name launched by the current application. swagger/doc.json 路径,如果有额外需求,Manual assignment is possible,如下:
url := ginSwagger.URL("http://127.0.0.1:8000/swagger/doc.json")
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
查看接口文档
After completing the above settings,我们重新启动服务端,在浏览器中访问 Swagger 的地址 http://127.0.0.1:8000/swagger/index.html,You can see in the picture above Swagger 文档展示,其主要分为三个部分,Project main information、Interface routing information、模型信息,These three parts together form our main content.
快速上手文档:swag使用指南
官方文档:swagger详细使用指南
ps:If you can't get up,hang a ladder
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在.深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小.自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前.因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担.添加下方名片,即可获取全套学习资料哦
边栏推荐
猜你喜欢

【面试题】从输入URL到游览器渲染完成,经历了什么

力扣 593. 有效的正方形

PowerCLi 通过自建PXE Server一键esxi7下批量部署常规New-VM

How to Install MySQL on Linux

@Transactional注解的失效场景

【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议

torch分布式训练

【pytorch记录】pytorch的分布式 torch.distributed.launch 命令在做什么呢

【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)

【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
随机推荐
"The C language games" mine clearance
[Yellow ah code] Introduction to MySQL - 3. I use select, the boss directly drives me to take the train home, and I still buy a station ticket
关于“算力”,这篇文章值得一看
MySql database optimization query tool
数组every和some方法的区别?
深度学习随机数设置,保证实验的可重复性
关于yum源的配置及更新
Flutter Paystack 所有选项实现
Ubuntu安装Mysql5.7
功能强大的国产Api管理工具
Spark 在 Yarn 上运行 Spark 应用程序
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Middle)--Search Suggestions
35-Jenkins-共享库应用
shell/bash脚本命令教程
Calculation example of matlab program iEEE9 node system for power flow calculation of AC-DC hybrid system based on alternate iteration method
SSM框架简单介绍
48页智慧城市规划蓝图 解决方案
7/28-7/29 Expectation + thinking + suffix array + ST table
【C#】判断字符串中是否包含指定字符或字符串(Contains/IndexOf)
重装系统后,hosts文件配置后不生效