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
>Solution :
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))