Skip to content

Latest commit

 

History

History
75 lines (66 loc) · 1.75 KB

3.md

File metadata and controls

75 lines (66 loc) · 1.75 KB

修饰器

简单的描述:一个修饰器函数,参数是函数,返回一个运行了这个参数函数的跟参数函数保持相同的函数。

如果是接口,那么就是一个修饰器函数,参数是一个接口,返回值还是这个接口。

func D(f func(s string))func(s string){
  return func(s string){
    f(s)
    fmt.Println("done")
  }
}

func main(){
  D(func(s string){
    fmt.Println(s)
  })("hello")
}

具体案例

http 处理 cookie 和 header 的案例:

func main(){
  http.HandleFunc("/",WithHeader(hello))
  http.HandleFunc("/s",WithCookie(hello))
  http.ListenAndServe(":8080",nil)
}

func hello(w http.ResponseWriter,r *http.Request){
  fmt.Fprintln(w,"hello")
}
func WithHeader(h http.HandlerFunc)http.HandlerFunc{
  return func(w http.ResponseWriter,r *http.Request){
    w.Header().Set("Server", "HelloServer")
    h(w,r)
  }
}
  
func WithCookie(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cookie := &http.Cookie{Name: "auth", Value: "123456", Path: "/"}
		http.SetCookie(w, cookie)
		h(w, r)
	}
}

多修饰器的 pipeline (串型调用)

type Hander func(http.HandlerFunc)http.HandlerFunc

func DealWith(h http.HandlerFunc,handlers ...Hander)http.HandlerFunc{
  for i := range handlers {
    d := handlers[len(handlers) -i-1]
    h = d(h) 
  }
  return h
}
func main(){
  http.HandleFunc("/",DealWith(hello,WithCookie,WithHeader))
  http.ListenAndServe(":8080",nil)
}