在网络请求之前执行函数

huangapple go评论87阅读模式
英文:

Execute function before web requests

问题

我正在尝试在每个网络请求之前执行一个函数。我有一个简单的网络服务器:

func h1(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h1")
}
func h2(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h2")
}    
func h3(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h3")
}    

func main() {
  http.HandleFunc("/", h1)
  http.HandleFunc("/foo", h2)
  http.HandleFunc("/bar", h3)
  
  /*
    注册一个在处理程序之前执行的函数,
    无论调用什么URL。
  */
  
  http.ListenAndServe(":8080", nil)
}

问题:有没有简单的方法来做到这一点?

英文:

I am trying to execute a function before every web request. I got a simple web server:

func h1(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h1")
}
func h2(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h2")
}    
func h3(w http.ResponseWriter, r *http.Request) {
  fmt.Pprintf("handler: %s\n", "h3")
}    

func main() {
  http.HandleFunc("/", h1)
  http.HandleFunc("/foo", h2)
  http.HandleFunc("/bar", h3)
  
  /*
    Register a function which is executed before the handlers,
    no matter what URL is called.
  */
  
  http.ListenAndServe(":8080", nil)
}

Question: Is there a simple way to do this?

答案1

得分: 4

将每个HandlerFunc包装起来。

func WrapHandler(f HandlerFunc) HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    // 在这里调用任何前置处理函数
    mySpecialFunc()
    f(w, r)
  }
}

http.HandleFunc("/", WrapHandler(h1))

由于在Go语言中函数是一等公民,所以很容易对它们进行包装、柯里化或者其他你想要做的操作。

英文:

Wrap each of your HandlerFuncs.

func WrapHandler(f HandlerFunc) HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    // call any pre handler functions here
    mySpecialFunc()
    f(w, r)
  }
}

http.HandleFunc("/", WrapHandler(h1))

Since Functions are first class values in Go it's easy to wrap them, curry them, or any other thing you may want to do with them.

huangapple
  • 本文由 发表于 2013年2月3日 21:22:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/14672926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定