Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 588
Trenton Trama Avatar asked May 09 '13 17:05

Trenton Trama


1 Answers

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)
}
like image 191
Jeremy Wall Avatar answered Sep 20 '22 05:09

Jeremy Wall