Home >Backend Development >Golang >Why is my Go `HandleFunc` called twice when using a web browser?
Unexpected Double Invocation of HttpHandler: HandleFunc
Introduction
When utilizing the http.ServeMux multiplexer in a Go web server, it's observed that a registered handler function (HandleFunc) is invoked twice for each request made from a web browser. This behavior is contrary to the intended functionality.
Problem
Upon implementing a basic web server with a handler function that increments a counter, it's observed that the counter is incremented twice for each browser request. However, when using curl, the handler is invoked only once as expected.
Cause
After logging the requests, it becomes evident that the browser also sends a request for /favicon.ico. This is a request for a small icon that is typically displayed in the browser's address bar or tab. As the ServeMux multiplexer matches all URLs by default, it invokes the registered handler for this additional request, resulting in the double invocation.
Solution
To prevent the handler from being invoked for the favicon.ico request, two approaches can be considered:
Add a Specific favicon.ico Handler:
func favicon(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "favicon.ico") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", hello) mux.HandleFunc("/favicon.ico", favicon) http.ListenAndServe(":8000", mux) }
By defining a separate handler for /favicon.ico, the hello handler will only be invoked for regular page requests.
Skip the Handler for Default Patterns:
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { hello(w, r) } })
This approach checks the URL.Path of the request and ensures the hello handler is invoked only when the path is exactly /.
The above is the detailed content of Why is my Go `HandleFunc` called twice when using a web browser?. For more information, please follow other related articles on the PHP Chinese website!