这李借鉴我同事写的一个调用链,看看如果个一个请求加上一个调用链,这个其实在其它编程里面都会用到,如果熟悉拦截器的对此会应该会更有体会
先看看测试代码
package main
import (
"fmt"
"net/http"
)
func main() {
http.ListenAndServe(":8080", regisry())
}
func Hello(rw http.ResponseWriter, req *http.Request){
//return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("hello world!"))
//})
}
func Authentication() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
fmt.Println("Authentication")
Hello(rw,req)
})
}
func Authorizer(handle http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
fmt.Println("Authorizer")
handle.ServeHTTP(rw, req)
})
}
func Step3(handle http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
fmt.Println("Step3")
handle.ServeHTTP(rw, req)
})
}
func Step4(handle http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
fmt.Println("Step4")
handle.ServeHTTP(rw, req)
})
}
func regisry() http.Handler {
h := Authentication()
h = Authorizer(h)
h = Step3(h)
h = Step4(h)
return h
}
启功服务,测试一下,
Step4
Step3
Authorizer
Authentication
输出如下,下面分析一个这个请求的过程,先看定义的过程,从下向上,创建一个Step4方法,这个里面传入的是Step3,那么在Step4方法执行完之后将会执行 Step3方法 ,以此类推,最后创建一个Authentication的方法,Authentication之后调用自己的业务方法。
这个就可以逐层去过滤请求了。上面的每层函数返回的h都是一个新的http handle,只是名称一样。