Go 语言的 Decorator
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() 函数。
在调用上有些难看。当然,如果要让代码容易读一些,可以这样:
hello := decorator(Hello)
hello("Hello")
再来看一个 HTTP 路由的例子:
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("Received Request %s from %s\n", r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, "Hello, World! "+r.URL.Path)
}
上面的代码中,我们写了多个函数。有写 HTTP 响应头的,有写认证 Cookie 的,有检查认证 Cookie 的,有打日志的……在使用过程中,我们可以把其嵌套起来使用,在修饰过的函数上继续修饰,这样就可以拼装出更复杂的功能。
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)
}
}
函数式编程之二,将工具函数作为type,作为函数入参。遍历,形成 pipline玩法。
当然,如果一层套一层不好看的话,我们可以使用 pipeline 的玩法,需要先写一个工具函数——用来遍历并调用各个 decorator:
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
}
就可以像下面这样使用了,pipeline 的功能也就出来了
http.HandleFunc("/v4/hello", Handler(hello,
WithServerHeader, WithBasicAuth, WithDebugLog))
因为 Go 语言不像 Python 和 Java,Python 是动态语言,而 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("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 ,就是需要修饰的函数。
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
}
// 声明函数签名
type MyFoo func(int, int, int) int
var myfoo MyFoo
Decorator(&myfoo, foo)
myfoo(1, 2, 3)
// 不声明函数签名
mybar := bar
Decorator(&mybar, bar)
mybar("hello,", "world!")
所谓的修饰器模式其实是在做下面的几件事。
表面上看,修饰器模式就是扩展现有的一个函数的功能,让它可以干一些其他的事,
或是在现有的函数功能上再附加上一些别的功能。
除了我们可以感受到函数式编程下的代码扩展能力,我们还能感受到函数的互相和随意拼装带来的好处。
但是深入看一下,我们不难发现,Decorator 这个函数其实是可以修饰几乎所有的函数的。
于是,这种可以通用于其它函数的编程方式,可以很容易地将一些非业务功能的、属于控制类型的代码给抽象出来(所谓的控制类型的代码就是像 for-loop,或是打日志,或是函数路由,或是求函数运行时间之类的非业务功能性的代码)。