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?
Wrap each of your HandlerFuncs.
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.