Kiril
Kiril

Reputation: 6229

Execute function before web requests

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?

Upvotes: 2

Views: 367

Answers (1)

Jeremy Wall
Jeremy Wall

Reputation: 25245

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.

Upvotes: 4

Related Questions