I'm using the following code:
func main() {
http.Handle("/", http.FileServer(http.Dir("./web-files")))
http.HandleFunc("/auth/verify", verify)
http.HandleFunc("/auth/login", login)
http.HandleFunc("/auth/signup", signup)
http.ListenAndServe(":8080", nil)
}
I'm new to go and what I want to do is that every time someone enters my webpage a function named updateCookies
runs.
I've tried to use http.HandleFunc("/", updateCookies)
but it didn't work cause I have already used http.Handle("/", http.FileServer(http.Dir("./web-files")))
Thanks
CodePudding user response:
The handler for the your application is http.DefaultServeMux. Wrap that handler with another handler that executes your code:
// wrap returns an http.Handler that wraps another http.Handler
func wrap(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Before hook.
updateCookies(w, r)
h.ServeHTTP(w, r) // call the wrapped handler
// After hook.
// Nothing for now.
}
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./web-files")))
http.HandleFunc("/auth/verify", verify)
http.HandleFunc("/auth/login", login)
http.HandleFunc("/auth/signup", signup)
http.ListenAndServe(":8080", wrap(http.DefaultServeMux))
}
I wrote the code to wrap an arbitrary handler because there's an easy transition to using your own http.ServeMux:
func main() {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("./web-files")))
mux.HandleFunc("/auth/verify", verify)
mux.HandleFunc("/auth/login", login)
mux.HandleFunc("/auth/signup", signup)
http.ListenAndServe(":8080", wrap(mux))
}
Any package can register a handler in http.DefaultServeMux. Creating your own mux ensures that you have complete control over the handlers running in your application.
CodePudding user response:
http.Handle
, http.HandleFunc
, and http.ListenAndServe
(with nil
as the second argument), use http.DefaultServeMux
for routing the requests to their respective handlers.
http.ListenAndServe
will use the default mux ONLY when the second argument passed to it is nil
. If a non-nil argument is provided then it will use that, instead of the default mux, to handle the incoming requests.
Given that http.ListenAndServe
's second parameter's type is the http.Handler
interface, you could simply pass updateCookies
to http.ListenAndServe
as the second argument (though you'll have to convert it explicitly to http.HandlerFunc
) and then modify updateCookies
to, at the end, pass the w
and the r
to the default mux.
func updateCookies(w http.ResponseWriter, r *http.Request) {
// ... [your original cookie code] ...
http.DefaultServeMux.ServeHTTP(w, r)
}
// ...
http.ListenAndServe(":8080", http.HandlerFunc(updateCookies))