GO语言的修饰器编程

简介: 之前写过一篇《Python修饰器的函数式编程》,这种模式很容易的可以把一些函数装配到另外一些函数上,可以让你的代码更为的简单,也可以让一些“小功能型”的代码复用性更高,让代码中的函数可以像乐高玩具那样自由地拼装。

之前写过一篇《Python修饰器的函数式编程》,这种模式很容易的可以把一些函数装配到另外一些函数上,可以让你的代码更为的简单,也可以让一些“小功能型”的代码复用性更高,让代码中的函数可以像乐高玩具那样自由地拼装。所以,一直以来,我对修饰器decoration这种编程模式情有独钟,这里写一篇Go语言相关的文章。

看过Python修饰器那篇文章的同学,一定知道这是一种函数式编程的玩法——用一个高阶函数来包装一下。多唠叨一句,关于函数式编程,可以参看我之前写过一篇文章《函数式编程》,这篇文章主要是,想通过从过程式编程的思维方式过渡到函数式编程的思维方式,从而带动更多的人玩函数式编程,所以,如果你想了解一下函数式编程,那么可以移步先阅读一下。所以,Go语言的修饰器编程模式,其实也就是函数式编程的模式。

不过,要提醒注意的是,Go 语言的“糖”不多,而且又是强类型的静态无虚拟机的语言,所以,无法做到像 Java 和 Python 那样的优雅的修饰器的代码。当然,也许是我才才疏学浅,如果你知道有更多的写法,请你一定告诉我。先谢过了。

简单示例

我们先来看一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main
import  "fmt"
func decorator(f func(s string)) func(s string) {
return  func(s string) {
fmt.Println( "Started" )
f(s)
fmt.Println( "Done" )
}
}
func Hello(s string) {
fmt.Println(s)
}
func main() {
decorator(Hello)( "Hello, World!" )
}

我们可以看到,我们动用了一个高阶函数 decorator(),在调用的时候,先把 Hello()函数传进去,然后其返回一个匿名函数,这个匿名函数中除了运行了自己的代码,也调用了被传入的 Hello() 函数。

这个玩法和 Python 的异曲同工,只不过,有些遗憾的是,Go 并不支持像 Python 那样的 @decorator 语法糖。所以,在调用上有些难看。当然,如果你要想让代码容易读一些,你可以这样:

1
2
hello := decorator(Hello)
hello( "Hello" )

我们再来看一个和计算运行时间的例子:

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
package main
import (
"fmt"
"reflect"
"runtime"
"time"
)
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( "--- Time Elapsed (%s): %v ---\n" ,
getFunctionName(f),  time .Since(t))
}( time .Now())
return  f(start, end)
}
}
func Sum1(start, end int64) int64 {
var sum int64
sum = 0
if  start > end {
start, end = end, start
}
for  i := start; i <= end; i++ {
sum += i
}
return  sum
}
func Sum2(start, end int64) int64 {
if  start > end {
start, end = end, start
}
return  (end - start + 1) * (end + start) / 2
}
func main() {
sum1 := timedSumFunc(Sum1)
sum2 := timedSumFunc(Sum2)
fmt.Printf( "%d, %d\n" , sum1(-10000, 10000000), sum2(-10000, 10000000))
}

关于上面的代码,有几个事说明一下:

1)有两个 Sum 函数,Sum1() 函数就是简单的做个循环,Sum2() 函数动用了数据公式。(注意:start 和 end 有可能有负数的情况)

2)代码中使用了 Go 语言的反射机器来获取函数名。

3)修饰器函数是 timedSumFunc()

运行后输出:

1
2
3
4
$ go run  time . sum .go
--- Time Elapsed (main.Sum1): 3.557469ms ---
--- Time Elapsed (main.Sum2): 291ns ---
49999954995000, 49999954995000

插播福利

1.近期整理了20G资源,包含产品/运营/测试/程序员/市场等,互联网从业者【工作必备干货技巧、行业专业书籍、面试真题宝典等】,获取方式:

  • 微信扫码关注公众号“非典型互联网”,转发文章到朋友圈,截图发至公众号后台,即可获取干货资源链接;

2.互联网人交流群:

  • 关注公众号“非典型互联网”,在公众号后台回复“入群”,人脉共享,一起交流;

HTTP 相关的一个示例

我们再来看一个处理 HTTP 请求的相关的例子。

先看一个简单的 HTTP Server 的代码。

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
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return  func(w http.ResponseWriter, r *http.Request) {
log .Println( "--->WithServerHeader()" )
w.Header().Set( "Server" "HelloServer v0.0.1" )
h(w, r)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
log .Printf( "Recieved Request %s from %s\n" , r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w,  "Hello, World! " +r.URL.Path)
}
func main() {
http.HandleFunc( "/v1/hello" , WithServerHeader(hello))
err := http.ListenAndServe( ":8080" , nil)
if  err != nil {
log .Fatal( "ListenAndServe: " , err)
}
}

上面代码中使用到了修饰模式,WithServerHeader() 函数就是一个 Decorator,其传入一个 http.HandlerFunc,然后返回一个改写的版本。上面的例子还是比较简单,用 WithServerHeader() 就可以加入一个 Response 的 Header。

于是,这样的函数我们可以写出好些个。如下所示,有写 HTTP 响应头的,有写认证 Cookie 的,有检查认证Cookie的,有打日志的……

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
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func WithServerHeader(h http.HandlerFunc) http.HandlerFunc {
return  func(w http.ResponseWriter, r *http.Request) {
log .Println( "--->WithServerHeader()" )
w.Header().Set( "Server" "HelloServer v0.0.1" )
h(w, r)
}
}
func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc {
return  func(w http.ResponseWriter, r *http.Request) {
log .Println( "--->WithAuthCookie()" )
cookie := &http.Cookie{Name:  "Auth" , Value:  "Pass" , Path:  "/" }
http.SetCookie(w, cookie)
h(w, r)
}
}
func WithBasicAuth(h http.HandlerFunc) http.HandlerFunc {
return  func(w http.ResponseWriter, r *http.Request) {
log .Println( "--->WithBasicAuth()" )
cookie, err := r.Cookie( "Auth" )
if  err != nil || cookie.Value !=  "Pass"  {
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( "--->WithDebugLog" )
r.ParseForm()
log .Println(r.Form)
log .Println( "path" , r.URL.Path)
log .Println( "scheme" , r.URL.Scheme)
log .Println(r.Form[ "url_long" ])
for  k, v := range r.Form {
log .Println( "key:" , k)
log .Println( "val:" , strings.Join(v,  "" ))
}
h(w, r)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
log .Printf( "Recieved Request %s from %s\n" , r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w,  "Hello, World! " +r.URL.Path)
}
func main() {
http.HandleFunc( "/v1/hello" , WithServerHeader(WithAuthCookie(hello)))
http.HandleFunc( "/v2/hello" , WithServerHeader(WithBasicAuth(hello)))
http.HandleFunc( "/v3/hello" , WithServerHeader(WithBasicAuth(WithDebugLog(hello))))
err := http.ListenAndServe( ":8080" , nil)
if  err != nil {
log .Fatal( "ListenAndServe: " , err)
}
}

多个修饰器的 Pipeline

在使用上,需要对函数一层层的套起来,看上去好像不是很好看,如果需要 decorator 比较多的话,代码会比较难看了。嗯,我们可以重构一下。

重构时,我们需要先写一个工具函数——用来遍历并调用各个 decorator:

1
2
3
4
5
6
7
8
9
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
}

然后,我们就可以像下面这样使用了。

1
2
http.HandleFunc( "/v4/hello" , Handler(hello,
WithServerHeader, WithBasicAuth, WithDebugLog))

这样的代码是不是更易读了一些?pipeline 的功能也就出来了。

泛型的修饰器

不过,对于 Go 的修饰器模式,还有一个小问题 —— 好像无法做到泛型,就像上面那个计算时间的函数一样,其代码耦合了需要被修饰的函数的接口类型,无法做到非常通用,如果这个事解决不了,那么,这个修饰器模式还是有点不好用的。

因为 Go 语言不像 Python 和 Java,Python是动态语言,而 Java 有语言虚拟机,所以他们可以干好些比较变态的事,然而 Go 语言是一个静态的语言,这意味着其类型需要在编译时就要搞定,否则无法编译。不过,Go 语言支持的最大的泛型是 interface{} 还有比较简单的 reflection 机制,在上面做做文章,应该还是可以搞定的。

废话不说,下面是我用 reflection 机制写的一个比较通用的修饰器(为了便于阅读,我删除了出错判断代码)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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( "before" )
out = targetFunc.Call(in)
fmt.Println( "after" )
return
})
decoratedFunc.Set(v)
return
}

上面的代码动用了 reflect.MakeFunc() 函数制出了一个新的函数其中的 targetFunc.Call(in) 调用了被修饰的函数。关于 Go 语言的反射机制,推荐官方文章 —— 《The Laws of Reflection》,在这里我不多说了。

上面这个 Decorator() 需要两个参数,

  • 第一个是出参 decoPtr ,就是完成修饰后的函数
  • 第二个是入参 fn ,就是需要修饰的函数

这样写是不是有些二?的确是的。不过,这是我个人在 Go 语言里所能写出来的最好的的代码了。如果你知道更多优雅的,请你一定告诉我!

好的,让我们来看一下使用效果。首先假设我们有两个需要修饰的函数:

1
2
3
4
5
6
7
8
9
func foo(a, b, c  int int  {
fmt.Printf( "%d, %d, %d \n" , a, b, c)
return  a + b + c
}
func bar(a, b string) string {
fmt.Printf( "%s, %s \n" , a, b)
return  a + b
}

然后,我们可以这样做:

1
2
3
4
type MyFoo func( int int int int
var myfoo MyFoo
Decorator(&myfoo, foo)
myfoo(1, 2, 3)

你会发现,使用 Decorator() 时,还需要先声明一个函数签名,感觉好傻啊。一点都不泛型,不是吗?

嗯。如果你不想声明函数签名,那么你也可以这样

1
2
3
mybar := bar
Decorator(&mybar, bar)
mybar( "hello," "world!" )

好吧,看上去不是那么的漂亮,但是 it works。看样子 Go 语言目前本身的特性无法做成像 Java 或 Python 那样,对此,我们只能多求 Go 语言多放糖了!

作者:陈皓,博客地址:https://coolshell.cn/articles/18190.html

目录
相关文章
|
14天前
|
Go
go语言中的数据类型
go语言中的数据类型
12 0
|
20天前
|
Go 开发者
掌握Go语言:Go语言结构体,精准封装数据,高效管理实体对象(22)
掌握Go语言:Go语言结构体,精准封装数据,高效管理实体对象(22)
|
20天前
|
安全 Go
掌握Go语言:Go语言通道,并发编程的利器与应用实例(20)
掌握Go语言:Go语言通道,并发编程的利器与应用实例(20)
|
20天前
|
存储 缓存 安全
掌握Go语言:Go语言中的字典魔法,高效数据检索与应用实例解析(18)
掌握Go语言:Go语言中的字典魔法,高效数据检索与应用实例解析(18)
|
20天前
|
Go
使用Go语言发邮件
使用Go语言发邮件
20 2
|
1月前
|
缓存 安全 Java
Go语言小细节
Go语言小细节
36 0
|
20天前
|
存储 安全 Go
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
|
1天前
|
数据采集 存储 Go
使用Go语言和chromedp库下载Instagram图片:简易指南
Go语言爬虫示例使用chromedp库下载Instagram图片,关键步骤包括设置代理IP、创建带代理的浏览器上下文及执行任务,如导航至用户页面、截图并存储图片。代码中新增`analyzeAndStoreImage`函数对图片进行分析和分类后存储。注意Instagram的反爬策略可能需要代码适时调整。
使用Go语言和chromedp库下载Instagram图片:简易指南
|
4天前
|
API Go
使用Go语言通过API获取代理IP并使用获取到的代理IP
使用Go语言通过API获取代理IP并使用获取到的代理IP
|
5天前
|
前端开发 Java Go
开发语言详解(python、java、Go(Golong)。。。。)
开发语言详解(python、java、Go(Golong)。。。。)

热门文章

最新文章