惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CERT Recently Published Vulnerability Notes
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
Cisco Talos Blog
Cisco Talos Blog
P
Proofpoint News Feed
H
Heimdal Security Blog
Help Net Security
Help Net Security
H
Help Net Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Palo Alto Networks Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
The GitHub Blog
The GitHub Blog
博客园_首页
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News: Ask HN
Hacker News: Ask HN
博客园 - 【当耐特】
J
Java Code Geeks
S
SegmentFault 最新的问题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
O
OpenAI News
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
B
Blog RSS Feed
V2EX - 技术
V2EX - 技术
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tenable Blog
PCI Perspectives
PCI Perspectives
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Hacker News
The Hacker News
Schneier on Security
Schneier on Security
Google Online Security Blog
Google Online Security Blog
美团技术团队
G
GRAHAM CLULEY
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 聂微东
W
WeLiveSecurity
Vercel News
Vercel News
S
Security Affairs
T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
博客园 - 司徒正美
G
Google Developers Blog
D
Docker
Webroot Blog
Webroot Blog

Mohuishou

如何实现支持多集群的 Kubernetes Operator? 第三方应用如何调用我们 kubebuilder 生成的自定义资源? Kubernetes 简明教程 k8s job 为何迟迟不能结束? Go 工程化(十一) 如何优雅的写出 repo 层代码 Go 工程化(十) 如何在整洁架构中使用事务? 给博客添加章节目录 使用 Notion Database 管理静态博客文章 一个普通 Go 开发的三年 4. localhost 就一定是 localhost 么? Go可用性(七) 总结: 一张图串联可用性知识点 Go可用性(六) 熔断 10. 总结 9. kubebuilder 进阶: 源码分析 8. kubebuilder 进阶: webhook 7. kubebuilder 进阶: 测试 6. kubebuilder 实战: status & event 5. kubebuilder 实战: CRUD 4. kustomize 简明教程 3. KubeBuilder 简明教程 2. Kind: 如何快速搭建本地 K8s 开发环境? 1. Operator概述: 如何对 Kubernetes 进行扩展 Go可用性(五) 自适应限流 Go可用性(四) 漏桶算法 Go可用性(三) 令牌桶的实现 rate/limt Go可用性(二) 令牌桶原理及使用 Go可用性(一) 隔离设计 Go并发编程(十二) Singleflight Go工程化(九) 项目重构实践 Go工程化(八) 单元测试 Go工程化(七) Go Module Go工程化(六) 配置管理 Go工程化(五) API 设计下: 基于 protobuf 自动生成 gin 代码 Go工程化(四) API 设计上: 项目结构 & 设计 Go工程化(三) 依赖注入框架 wire Go工程化(二) 项目目录结构 Go工程化(一) 架构整洁之道阅读笔记 Go并发编程(十一) 总结 Go并发编程(十) 深入理解 Channel Go并发编程(九) 深入理解 Context Go并发编程(八) 深入理解 sync.Once Go并发编程(七) 深入理解 errgroup Go并发编程(六) 深入理解 WaitGroup Go并发编程(五) 深入理解 sync/atomic Go并发编程(四) 深入理解 Mutex Go并发编程(三) data race Go并发编程(二) Go 内存模型 Go并发编程(一) goroutine Go错误处理最佳实践 微服务(二) 服务发现&多租户 微服务(一) 微服务概览 5. 栈下: 深入理解 defer 4. 栈上: 如何实现一个计算器 Go Struct 初始化风格的抉择 3. 数组下: 使用 GDB 调试 Golang 代码 2. 数组上: 深入理解 slice 1. 链表: 深入理解container/list&LRU缓存的实现 Go设计模式24-总结(更新完毕) Go设计模式23-中介模式 Go设计模式22-解释器模式 Go设计模式21-命令模式 Go设计模式20-备忘录模式 Go设计模式19-访问者模式 Go设计模式18-迭代器模式 Go设计模式17-状态模式 Go设计模式16-职责链模式(Gin的中间件实现) Go设计模式15-策略模式 Go模板模式14-模板模式 Go设计模式13-观察者模式(实现简单的EventBus) Go设计模式12-享元模式 Go设计模式11-组合模式 Go设计模式10-门面模式 Go设计模式09-适配器模式 Go设计模式08-装饰器模式 Go设计模式07-桥接模式 Go设计模式06-代理模式(generate实现类似动态代理) Go设计模式05-创建型模式总结 Go设计模式04-原型模式 Go设计模式03-建造者模式 Go设计模式02-工厂模式&DI容器 笔记-让你最快速地改善代码质量的20条编程规范 Go设计模式01-单例模式 一点拙见-如何写好一个技术预研报告? Go Web小技巧(四)在单个仓库中支持多个 go mod 模块 Go Web 小技巧(三)Gin 参数绑定 Go Web 小技巧(二)GORM 使用自定义类型 善用工具之postman高级用法概述 go generate and ast hexo-next-algolia-search全文搜索 docker镜像瘦身&优化 GORM避坑指南之含关联关系的更新 Github Actions介绍&自动构建Github Pages博客 在blog中内嵌在线PPT 记一次net http内存泄漏 使用TravisCI自动部署Blog 使用Goland调试Go程序 一个十分边缘的gorm的bug Httprouter介绍及源码阅读 Gin源码阅读 从0.1开始
Go Web 小技巧(一)简化Gin接口代码
mohuishou <1@lailin.xyz> · 2019-10-26 · via Mohuishou

注:本文已发布超过一年,请注意您所使用工具的相关版本是否适用

不知道大家在使用 Gin 构建 API 服务时有没有这样的问题:

  1. 参数绑定的环节可不可以自动处理?
  2. 错误可不可以直接返回,不想写空 return, 漏写就是 bug

本文通过简单地封装,利用 go 的接口特性,提供一个解决上述两个问题的思路

解决过程

刚开始时写 API 服务时

我们刚开始使用 Gin 写 API 服务时,一般会按照官方文档上的 🌰 这么写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// User 用户结构
type User struct {
UserName string
}

// CreateUser 创建用户
func CreateUser(ctx *gin.Context) {
var params User
if err := ctx.ShouldBind(&params); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"msg": "参数错误",
})

logrus.Errorf("params err, %v", params)
return
}

// 一些其他的业务逻辑 ...

ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "创建成功",
})
}

func main() {
r := gin.Default()
r.POST("user", CreateUser)
if err := r.Run(":8080"); err != nil {
logrus.Fatalf("can not start serve: %v", err)
}
}

封装返回值

我们写了一段时间之后,会发现,我们的返回值的结构是固定的,为什么不抽象一下呢,所以我们创建了一个结构体 Resp ,并且封装了两个方法用于成功和失败这两种状态的返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// resp.go

// Resp 返回
type Resp struct {
Code int
Msg string
Data interface{}
}

// ErrorResp 错误返回值
func ErrorResp(ctx *gin.Context, code int, msg string, data ...interface{}) {
resp(ctx, code, msg, data...)
}

// SuccessResp 正确返回值
func SuccessResp(ctx *gin.Context, msg string, data ...interface{}) {
resp(ctx, 0, msg, data...)
}

// resp 返回
func resp(ctx *gin.Context, code int, msg string, data ...interface{}) {
resp := Resp{
Code: code,
Msg: msg,
Data: data,
}
if len(data) == 1 {
resp.Data = data[0]
}
ctx.JSON(http.StatusOK, resp)
}

添加这个方法之后,我们再看一下 CreateUser 这个方法,成功的从 16 行变到了 12 行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// main.go
// CreateUser 创建用户
func CreateUser(ctx *gin.Context) {
var params User
if err := ctx.ShouldBind(&params); err != nil {
ErrorResp(ctx, 400, "参数错误")
logrus.Errorf("params err, %v", params)
return
}

// 一些其他的业务逻辑 ...

SuccessResp(ctx, "创建成功")
}

两个痛点

上面的方法还不够完整,我们还是有许多重复的逻辑,可以发现我们在写的绝大多数 API 大概都是这样:

  1. 参数绑定 & 校验
  2. 业务逻辑
  3. 返回

这里面有两个痛点:

  1. 参数绑定的环节可不可以自动处理?

  2. 错误可不可以直接返回,不想写空 return, 漏写就是 bug

    1
    2
    3
    4
    5
    6
    7
    8
    // 不想写大量这种重复的代码
    var params User
    if err := ctx.ShouldBind(&params); err != nil {
    // 下面这三行是不是可以合并成一行
    ErrorResp(ctx, 400, "参数错误")
    logrus.Errorf("params err, %v", params)
    return
    }

使用接口封装请求

上面的这两个痛点我们可以通过一个辅助函数解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Requester 请求
type Requester interface {
Request(ctx *gin.Context) (*Resp, error)
}

// Handle 请求
func Handle(r Requester) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp, err := request(r, ctx)
if err != nil {
var code *errcode.Error
if !errors.As(err, &code) {
code = errcode.Unknown.Wrap(err)
}

resp = &Resp{
Code: code.Code,
Msg: code.String(),
}
_ = ctx.Error(err)
}
ctx.JSON(http.StatusOK, resp)
}
}

func request(r Requester, ctx *gin.Context) (*controller.Resp, error) {
// 参数绑定
if err := ctx.ShouldBind(r); err != nil {
return nil, errcode.ErrParams.Wrap(err)
}

return r.Request(ctx)
}

这样我们只需要实现这个 Requester, 写 API 时只需要关注业务逻辑就可以了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// CreateUser 创建用户
type CreateUser struct {
UserName string
}

func (u *User) Request(ctx *gin.Context) (*Resp, error) {
// 业务逻辑

// 返回成功值
}

func main() {
r := gin.Default()
r.POST("user", Handle(&CreateUser))
if err := r.Run(":8080"); err != nil {
logrus.Fatalf("can not start serve: %v", err)
}
}

上面的代码有一个 bug 不知道大家发现没有,我们上一次请求的参数会被带到下一次请求当中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Handle 请求
func Handle(r Requester) gin.HandlerFunc {
return func(ctx *gin.Context) {
// 创建一个新的 Requester, 避免将上一次的参数带到下一次当中
if reflect.TypeOf(r).Kind() != reflect.Ptr {
panic("must be a pointer")
}

req := reflect.New(reflect.ValueOf(r).Elem().Type()).Interface().(Requester)
resp, err := request(req, ctx)
if err != nil {
var code *errcode.Error
if !errors.As(err, &code) {
code = errcode.Unknown.Wrap(err)
}

resp = &Resp{
Code: code.Code,
Msg: code.String(),
}
_ = ctx.Error(err)
}
ctx.JSON(http.StatusOK, resp)
}
}

总结

大概这样差不多就 ok 了,还有很多可以完善的点,这里有一些思路,有的已经做了,有的还在路上

  1. 每次注册都写 Handle(&CreateUser) 还是有点麻烦?

    可以封装一下 gin.IRouter 这个接口,这样注册接口就可以和原来一样了

  2. 参数绑定如果我需要多次绑定怎么办?

    可以添加一个接口,如果实现了这个接口就执行以下,对于有特殊的参数校验之类的也可以采用类似的方式处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    type Binder interface {
    Bind(ctx *gin.Context) error
    }

    func request(r Requester, ctx *gin.Context) (*controller.Resp, error) {
    // 参数绑定
    if err := ctx.ShouldBind(r); err != nil {
    return nil, errcode.ErrParams.Wrap(err)
    }

    // 其余参数绑定
    if b, ok := r.(Binder); ok {
    if err := b.Bind(api); err != nil {
    return nil, errcode.ErrParams.Wrap(err)
    }
    }

    return r.Request(ctx)
    }

  3. 怎么输出 API 文档?

    可以和 swagger 之类的 API 文档结合, 利用 go generate 自动生成,顺便可以连接口注册都不用了,添加一行注释,自动注册接口,并且输出接口文档

    1
    2
    // @Router put /api/v1/user
    func(u *User) Request(ctx *gin.Context) (*Resp, error)
  4. 能不能减少 CURD 代码?

    可以实现,只需要采用约定的项目接口,可以 利用 go generate 直接自动生成简单的 CURD 代码

关注我获取更新

猜你喜欢