背景
在开发中,如果需要封装一些组件,但是不想通过 before&after 这类切面来操作,就需要有 middleware 的支撑。其实middleware 的设计非常简单,但是网上很多都是讲 web 的,好像没有非 web 项目的,这里就写一个吧
middleware
与 before&after 这种场景不太一样,middleware 希望知道每个操作前后带来的变化,“视野”会更完整
下面是 middleware 的流程
demo:
package main
import (
"fmt"
)
type TaskHandler func(data *string)
type TaskMiddleware func(handler TaskHandler) TaskHandler
func Middleware1(next TaskHandler) TaskHandler {
return TaskHandler(func(a *string) {
fmt.Println("print input 1", *a)
*a = "mid1"
next(a)
fmt.Println("print output 1", *a)
})
}
func Middleware2(next TaskHandler) TaskHandler {
return TaskHandler(func(a *string) {
fmt.Println("print input 2", *a)
*a = "mid2"
next(a)
fmt.Println("print output 2", *a)
})
}
func main() {
middlewares := make([]TaskMiddleware, 0)
middlewares = append(middlewares, Middleware1, Middleware2)
handler := func(a *string) {
fmt.Println("real", *a)
}
for i := len(middlewares) - 1; i >= 0; i-- {
handler = middlewares[i](handler)
}
a1 := "haha"
handler(&a1)
}
输出
$ go run main.go
print input 1 haha
print input 2 mid1
real mid2
print output 2 mid2
print output 1 mid2