Appengine with Go: 是否有类似的 http.Handle 预处理钩子或类似的东西?

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

Appengine with Go: Is there a http.Handle prehook or something similar?

问题

假设我有以下的初始化函数来路由请求。

func init() {
    http.HandleFunc("/user", handler1)
    http.HandleFunc("/user/profile", handler2)
    http.HandleFunc("/user/post", handler3)
    ....
    ....
}

所有这些都需要我有用户的个人资料。

我知道我可以这样做

func handler1(w http.ResponseWriter, r *http.Request) {
    getUserdata()
    //实际的处理程序代码
    ...
    ...
}

但是,有没有一种方法可以在每个处理程序中不放置函数调用的情况下获取数据?这是Go是否希望你首先这样做的事情吗?

英文:

Suppose I have the following init function routing requests.

func init() {
    http.HandleFunc("/user", handler1)
    http.HandleFunc("/user/profile", handler2)
    http.HandleFunc("/user/post", handler3)
    ....
    ....
}

All of these require that I have the user's profile.

I know I can

func handler1(w http.ResponseWriter, r *http.Request) {
    getUserdata()
    //Actual handler code
    ...
    ...
}

But, is there a way I can get the data without putting the function call in every handler? Is this even something Go would want you to do in the first place?

答案1

得分: 10

你有两个选择。

  1. 你可以实现http.Handler接口
  2. 你可以用一个包装器HandleFunc包装所有的http.HandlerFunc

由于看起来你想要简单的东西,我将说明包装器的用法

func Prehook(f http.HandlerFunc) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    getUserData()
    f(w, r)
  }
}

func init() {
    // 在处理程序之前调用getUserData()
    http.HandleFunc("/user", Prehook(handler1))
    // 在处理程序之前不要调用getUserData()
    http.HandleFunc("/user/profile", handler2)
}
英文:

You have two options.

  1. You can inplement the http.Handler interface
  2. You Wrap all your http.HandlerFunc with a wrapper HandleFunc.

Since it looks like you want something simple I'll illustrate the WRapper

func Prehook(f http.HandlerFunc) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    getUserData()
    f(w, r)
  }
}

func init() {
    // use getUserData() call before your handler
    http.HandleFunc("/user", Prehook(handler1))
    // Don't use getUserData call before your handler
    http.HandleFunc("/user/profile", handler2)
}

huangapple
  • 本文由 发表于 2013年5月10日 01:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/16467716.html
匿名

发表评论

匿名网友

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

确定