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?
You have two options.
http.Handler
interfacehttp.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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With