Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run a specific function each time someone enters my website in go?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading