CategoryResourceRepost/极客时间专栏/左耳听风/Go语言编程模式/113 | Go编程模式:修饰器.md
louzefeng d3828a7aee mod
2024-07-11 05:50:32 +00:00

352 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<audio id="audio" title="113 | Go编程模式修饰器" controls="" preload="none"><source id="mp3" src="https://static001.geekbang.org/resource/audio/8d/c4/8d1a208b58df95699dafaee9c6f49bc4.mp3"></audio>
你好,我是陈皓,网名左耳朵耗子。
之前,我写过一篇文章《[Python修饰器的函数式编程](https://coolshell.cn/articles/11265.html)》,这种模式可以很轻松地把一些函数装配到另外一些函数上,让你的代码更加简单,也可以让一些“小功能型”的代码复用性更高,让代码中的函数可以像乐高玩具那样自由地拼装。
所以一直以来我都对修饰器Decoration这种编程模式情有独钟这节课我们就来聊聊Go语言的修饰器编程模式。
如果你看过我刚说的文章,就一定知道,这是一种函数式编程的玩法——用一个高阶函数来包装一下。
多唠叨一句,关于函数式编程,我之前还写过一篇文章《[函数式编程](https://coolshell.cn/articles/10822.html)》这篇文章主要是想通过详细介绍从过程式编程的思维方式过渡到函数式编程的思维方式带动更多的人玩函数式编程。所以如果你想了解一下函数式编程那么可以点击链接阅读一下这篇文章。其实Go语言的修饰器编程模式也就是函数式编程的模式。
不过要提醒你注意的是Go 语言的“糖”不多,而且又是强类型的静态无虚拟机的语言,所以,没有办法做到像 Java 和 Python 那样写出优雅的修饰器的代码。当然,也许是我才疏学浅,如果你知道更多的写法,请你一定告诉我。先谢过了。
## 简单示例
我们先来看一个示例:
```
package main
import &quot;fmt&quot;
func decorator(f func(s string)) func(s string) {
return func(s string) {
fmt.Println(&quot;Started&quot;)
f(s)
fmt.Println(&quot;Done&quot;)
}
}
func Hello(s string) {
fmt.Println(s)
}
func main() {
decorator(Hello)(&quot;Hello, World!&quot;)
}
```
可以看到,我们动用了一个高阶函数 `decorator()`,在调用的时候,先把 `Hello()` 函数传进去,然后会返回一个匿名函数。这个匿名函数中除了运行了自己的代码,也调用了被传入的 `Hello()` 函数。
这个玩法和 Python 的异曲同工只不过有些遗憾的是Go 并不支持像 Python 那样的 `@decorator` 语法糖。所以,在调用上有些难看。当然,如果你想让代码更容易读,你可以这样写:
```
hello := decorator(Hello)
hello(&quot;Hello&quot;)
```
我们再来看一个计算运行时间的例子:
```
package main
import (
&quot;fmt&quot;
&quot;reflect&quot;
&quot;runtime&quot;
&quot;time&quot;
)
type SumFunc func(int64, int64) int64
func getFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func timedSumFunc(f SumFunc) SumFunc {
return func(start, end int64) int64 {
defer func(t time.Time) {
fmt.Printf(&quot;--- Time Elapsed (%s): %v ---\n&quot;,
getFunctionName(f), time.Since(t))
}(time.Now())
return f(start, end)
}
}
func Sum1(start, end int64) int64 {
var sum int64
sum = 0
if start &gt; end {
start, end = end, start
}
for i := start; i &lt;= end; i++ {
sum += i
}
return sum
}
func Sum2(start, end int64) int64 {
if start &gt; end {
start, end = end, start
}
return (end - start + 1) * (end + start) / 2
}
func main() {
sum1 := timedSumFunc(Sum1)
sum2 := timedSumFunc(Sum2)
fmt.Printf(&quot;%d, %d\n&quot;, sum1(-10000, 10000000), sum2(-10000, 10000000))
}
```
关于这段代码,有几点我要说明一下:
1. 有两个 Sum 函数,`Sum1()` 函数就是简单地做个循环,`Sum2()` 函数动用了数据公式注意start 和 end 有可能有负数);
1. 代码中使用了 Go 语言的反射机制来获取函数名;
1. 修饰器函数是 `timedSumFunc()`
运行后输出:
```
$ go run time.sum.go
--- Time Elapsed (main.Sum1): 3.557469ms ---
--- Time Elapsed (main.Sum2): 291ns ---
49999954995000, 49999954995000
```
## HTTP 相关的一个示例
接下来,我们再看一个处理 HTTP 请求的相关例子。
先看一个简单的 HTTP Server 的代码:
```
package main
import (
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;strings&quot;
)
func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(&quot;---&gt;WithServerHeader()&quot;)
w.Header().Set(&quot;Server&quot;, &quot;HelloServer v0.0.1&quot;)
h(w, r)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
log.Printf(&quot;Recieved Request %s from %s\n&quot;, r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, &quot;Hello, World! &quot;+r.URL.Path)
}
func main() {
http.HandleFunc(&quot;/v1/hello&quot;, WithServerHeader(hello))
err := http.ListenAndServe(&quot;:8080&quot;, nil)
if err != nil {
log.Fatal(&quot;ListenAndServe: &quot;, err)
}
}
```
这段代码中使用到了修饰器模式,`WithServerHeader()` 函数就是一个 Decorator它会传入一个 `http.HandlerFunc`,然后返回一个改写的版本。这个例子还是比较简单的,用 `WithServerHeader()` 就可以加入一个 Response 的 Header。
所以,这样的函数我们可以写出好多。如下所示,有写 HTTP 响应头的,有写认证 Cookie 的有检查认证Cookie的有打日志的……
```
package main
import (
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;strings&quot;
)
func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(&quot;---&gt;WithServerHeader()&quot;)
w.Header().Set(&quot;Server&quot;, &quot;HelloServer v0.0.1&quot;)
h(w, r)
}
}
func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(&quot;---&gt;WithAuthCookie()&quot;)
cookie := &amp;http.Cookie{Name: &quot;Auth&quot;, Value: &quot;Pass&quot;, Path: &quot;/&quot;}
http.SetCookie(w, cookie)
h(w, r)
}
}
func WithBasicAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(&quot;---&gt;WithBasicAuth()&quot;)
cookie, err := r.Cookie(&quot;Auth&quot;)
if err != nil || cookie.Value != &quot;Pass&quot; {
w.WriteHeader(http.StatusForbidden)
return
}
h(w, r)
}
}
func WithDebugLog(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(&quot;---&gt;WithDebugLog&quot;)
r.ParseForm()
log.Println(r.Form)
log.Println(&quot;path&quot;, r.URL.Path)
log.Println(&quot;scheme&quot;, r.URL.Scheme)
log.Println(r.Form[&quot;url_long&quot;])
for k, v := range r.Form {
log.Println(&quot;key:&quot;, k)
log.Println(&quot;val:&quot;, strings.Join(v, &quot;&quot;))
}
h(w, r)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
log.Printf(&quot;Recieved Request %s from %s\n&quot;, r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, &quot;Hello, World! &quot;+r.URL.Path)
}
func main() {
http.HandleFunc(&quot;/v1/hello&quot;, WithServerHeader(WithAuthCookie(hello)))
http.HandleFunc(&quot;/v2/hello&quot;, WithServerHeader(WithBasicAuth(hello)))
http.HandleFunc(&quot;/v3/hello&quot;, WithServerHeader(WithBasicAuth(WithDebugLog(hello))))
err := http.ListenAndServe(&quot;:8080&quot;, nil)
if err != nil {
log.Fatal(&quot;ListenAndServe: &quot;, err)
}
}
```
## 多个修饰器的 Pipeline
在使用上,需要对函数一层层地套起来,看上去好像不是很好看,如果需要修饰器比较多的话,代码就会比较难看了。不过,我们可以重构一下。
重构时,我们需要先写一个工具函数,用来遍历并调用各个修饰器:
```
type HttpHandlerDecorator func(http.HandlerFunc) http.HandlerFunc
func Handler(h http.HandlerFunc, decors ...HttpHandlerDecorator) http.HandlerFunc {
for i := range decors {
d := decors[len(decors)-1-i] // iterate in reverse
h = d(h)
}
return h
}
```
然后,我们就可以像下面这样使用了:
```
http.HandleFunc(&quot;/v4/hello&quot;, Handler(hello,
WithServerHeader, WithBasicAuth, WithDebugLog))
```
这样的代码是不是更易读了一些Pipeline 的功能也就出来了。
## 泛型的修饰器
不过,对于 Go 的修饰器模式,还有一个小问题,那就是好像无法做到泛型。比如上面那个计算时间的函数,其代码耦合了需要被修饰的函数的接口类型,无法做到非常通用。如果这个问题解决不了,那么,这个修饰器模式还是有点不好用的。
因为 Go 语言不像 Python 和 JavaPython是动态语言而 Java 有语言虚拟机所以它们可以实现一些比较“变态”的事。但是Go 语言是一个静态的语言这就意味着类型需要在编译时就搞定否则无法编译。不过Go 语言支持的最大的泛型是 `interface{}` ,还有比较简单的 Reflection 机制,在上面做做文章,应该还是可以搞定的。
废话不说,下面是我用 Reflection 机制写的一个比较通用的修饰器(为了便于阅读,我删除了出错判断代码):
```
func Decorator(decoPtr, fn interface{}) (err error) {
var decoratedFunc, targetFunc reflect.Value
decoratedFunc = reflect.ValueOf(decoPtr).Elem()
targetFunc = reflect.ValueOf(fn)
v := reflect.MakeFunc(targetFunc.Type(),
func(in []reflect.Value) (out []reflect.Value) {
fmt.Println(&quot;before&quot;)
out = targetFunc.Call(in)
fmt.Println(&quot;after&quot;)
return
})
decoratedFunc.Set(v)
return
}
```
这段代码动用了 `reflect.MakeFunc()` 函数,创造了一个新的函数,其中的 `targetFunc.Call(in)` 调用了被修饰的函数。关于 Go 语言的反射机制,你可以阅读下官方文章[**The Laws of Reflection**](https://blog.golang.org/laws-of-reflection),我就不多说了。
这个 `Decorator()` 需要两个参数:
- 第一个是出参 `decoPtr` ,就是完成修饰后的函数;
- 第二个是入参 `fn` ,就是需要修饰的函数。
这样写是不是有些“傻”?的确是的。不过,这是我个人在 Go 语言里所能写出来的最好的代码了。如果你知道更多优雅的写法,请你要一定告诉我!
好了,让我们来看一下使用效果。首先,假设我们有两个需要修饰的函数:
```
func foo(a, b, c int) int {
fmt.Printf(&quot;%d, %d, %d \n&quot;, a, b, c)
return a + b + c
}
func bar(a, b string) string {
fmt.Printf(&quot;%s, %s \n&quot;, a, b)
return a + b
}
```
然后,我们可以这样做:
```
type MyFoo func(int, int, int) int
var myfoo MyFoo
Decorator(&amp;myfoo, foo)
myfoo(1, 2, 3)
```
你会发现,使用 `Decorator()` 时,还需要先声明一个函数签名,感觉好傻啊,一点都不泛型,不是吗?
如果你不想声明函数签名,就可以这样:
```
mybar := bar
Decorator(&amp;mybar, bar)
mybar(&quot;hello,&quot;, &quot;world!&quot;)
```
好吧,看上去不是那么漂亮,但是 it works。
看样子 Go 语言目前本身的特性无法做成像 Java 或 Python 那样对此我们只能期待Go 语言多放“糖”了!
Again 如果你有更好的写法,请你一定要告诉我。
好了,这节课就到这里。如果你觉得今天的内容对你有所帮助,欢迎你帮我分享给更多人。