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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
S
SegmentFault 最新的问题
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
博客园 - 叶小钗
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
腾讯CDC
博客园 - 聂微东
D
DataBreaches.Net
博客园 - Franky
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
量子位
宝玉的分享
宝玉的分享
D
Docker
T
Tailwind CSS Blog
IT之家
IT之家
Engineering at Meta
Engineering at Meta
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Project Zero
Project Zero
Microsoft Azure Blog
Microsoft Azure Blog
AWS News Blog
AWS News Blog
Google DeepMind News
Google DeepMind News
H
Heimdal Security Blog
W
WeLiveSecurity
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
有赞技术团队
有赞技术团队
Simon Willison's Weblog
Simon Willison's Weblog
NISL@THU
NISL@THU
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
T
Threatpost
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
S
Securelist

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设计模式05-创建型模式总结 Go设计模式04-原型模式 Go设计模式03-建造者模式 Go设计模式02-工厂模式&DI容器 笔记-让你最快速地改善代码质量的20条编程规范 Go设计模式01-单例模式 一点拙见-如何写好一个技术预研报告? Go Web小技巧(四)在单个仓库中支持多个 go mod 模块 Go Web 小技巧(三)Gin 参数绑定 Go Web 小技巧(二)GORM 使用自定义类型 Go Web 小技巧(一)简化Gin接口代码 善用工具之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设计模式06-代理模式(generate实现类似动态代理)
Mohuishou · 2020-09-06 · via Mohuishou

接下来会通过 golang 实现静态代理,有 Golang 和 java 的差异性,我们无法比较方便的利用反射实现动态代理,但是我们可以利用** go generate **实现类似的效果,并且这样实现有两个比较大的好处,一个是有静态代码检查,我们在编译期间就可以及早发现问题,第二个是性能会更好。

关于 go generate 之前已经写过一篇入门的介绍文章: go generate and ast,这里就不再赘述了,如果对相关的知识点不太清楚,可以先看前面的那篇文章。
注意: 在真实的项目中并不推荐这么做,因为有点得不偿失,本文只是在探讨一种可能性,并且可以复习一下 go 语法树先关的知识点
接下来我们先来看看需求。

动态代理相比静态代理主要就是为了解决生产力,将我们从繁杂的重复劳动中解放出来,正好,在 Go 中 Generate 也是干这个活的
如下面的代码所示,我们的 generate 会读取 struct 上的注释,如果出现 @proxy 接口名  的注释,我们就会为这个 struct 生成一个 proxy 类,同时实现相同的接口,这个接口就是在注释中指定的接口

接来下我们会简单的实现这个需求,由于篇幅和时间的关系,我们会略过一些检查之类的代码,例如 User  是否真正实现了 IUser  这种情况。
代码有点长,主要思路:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package proxy

import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"strings"
"text/template"
)

func generate(file string) (string, error) {
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
return "", err
}

// 获取代理需要的数据
data := proxyData{
Package: f.Name.Name,
}

// 构建注释和 node 的关系
cmap := ast.NewCommentMap(fset, f, f.Comments)
for node, group := range cmap {
// 从注释 @proxy 接口名,获取接口名称
name := getProxyInterfaceName(group)
if name == "" {
continue
}

// 获取代理的类名
data.ProxyStructName = node.(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Name.Name

// 从文件中查找接口
obj := f.Scope.Lookup(name)

// 类型转换,注意: 这里没有对断言进行判断,可能会导致 panic
t := obj.Decl.(*ast.TypeSpec).Type.(*ast.InterfaceType)

for _, field := range t.Methods.List {
fc := field.Type.(*ast.FuncType)

// 代理的方法
method := &proxyMethod{
Name: field.Names[0].Name,
}

// 获取方法的参数和返回值
method.Params, method.ParamNames = getParamsOrResults(fc.Params)
method.Results, method.ResultNames = getParamsOrResults(fc.Results)

data.Methods = append(data.Methods, method)
}
}

// 生成文件
tpl, err := template.New("").Parse(proxyTpl)
if err != nil {
return "", err
}

buf := &bytes.Buffer{}
if err := tpl.Execute(buf, data); err != nil {
return "", err
}

// 使用 go fmt 对生成的代码进行格式化
src, err := format.Source(buf.Bytes())
if err != nil {
return "", err
}

return string(src), nil
}

// getParamsOrResults 获取参数或者是返回值
// 返回带类型的参数,以及不带类型的参数,以逗号间隔
func getParamsOrResults(fields *ast.FieldList) (string, string) {
var (
params []string
paramNames []string
)

for i, param := range fields.List {
// 循环获取所有的参数名
var names []string
for _, name := range param.Names {
names = append(names, name.Name)
}

if len(names) == 0 {
names = append(names, fmt.Sprintf("r%d", i))
}

paramNames = append(paramNames, names...)

// 参数名加参数类型组成完整的参数
param := fmt.Sprintf("%s %s",
strings.Join(names, ","),
param.Type.(*ast.Ident).Name,
)
params = append(params, strings.TrimSpace(param))
}

return strings.Join(params, ","), strings.Join(paramNames, ",")
}

func getProxyInterfaceName(groups []*ast.CommentGroup) string {
for _, commentGroup := range groups {
for _, comment := range commentGroup.List {
if strings.Contains(comment.Text, "@proxy") {
interfaceName := strings.TrimLeft(comment.Text, "// @proxy ")
return strings.TrimSpace(interfaceName)
}
}
}
return ""
}

// 生成代理类的文件模板
const proxyTpl = `
package {{.Package}}

type {{ .ProxyStructName }}Proxy struct {
child *{{ .ProxyStructName }}
}

func New{{ .ProxyStructName }}Proxy(child *{{ .ProxyStructName }}) *{{ .ProxyStructName }}Proxy {
return &{{ .ProxyStructName }}Proxy{child: child}
}

{{ range .Methods }}
func (p *{{$.ProxyStructName}}Proxy) {{ .Name }} ({{ .Params }}) ({{ .Results }}) {
// before 这里可能会有一些统计的逻辑
start := time.Now()

{{ .ResultNames }} = p.child.{{ .Name }}({{ .ParamNames }})

// after 这里可能也有一些监控统计的逻辑
log.Printf("user login cost time: %s", time.Now().Sub(start))

return {{ .ResultNames }}
}
{{ end }}
`

type proxyData struct {
// 包名
Package string
// 需要代理的类名
ProxyStructName string
// 需要代理的方法
Methods []*proxyMethod
}

// proxyMethod 代理的方法
type proxyMethod struct {
// 方法名
Name string
// 参数,含参数类型
Params string
// 参数名
ParamNames string
// 返回值
Results string
// 返回值名
ResultNames string
}