When using this Go web server to count its invocations, it prints uneven numbers instead of the expected sequence of 1, 2, 3...:
package mainimport ( "fmt" "net/http" ) var calls int // HelloWorld print the times being called. func HelloWorld(w http.ResponseWriter, r *http.Request){ calls++ fmt.Fprintf(w, "You've called me %d times", calls) } func main() { fmt.Printf("Started server at http://localhost%v.\n", 5000) http.HandleFunc("/", HelloWorld) http.ListenAndServe(":5000", nil) }
The observed behavior is due to the browser's handling of the favicon.ico file. When a web page is loaded, the browser makes a request for this file, which is a standard website icon. Since the web server provided by the given code does not serve a valid favicon.ico, the browser repeatedly requests it.
As each request counts as an invocation of the HelloWorld handler, the call count increases even when the user only refreshes the page once. The favicon.ico requests are sandwiched between invocations of the root URL ("/") handled by the HelloWorld function, resulting in the uneven number sequence.
To prevent this, one can check the request path in the HelloWorld function and ignore requests for favicon.ico:
func HelloWorld(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { return } count := atomic.AddInt64(&calls, 1) fmt.Fprintf(w, "You've called me %d times", count) }
This modification ensures that the call count increments only for requests to the root URL. Alternatively, one could disable favicon.ico requests altogether in the web server configuration.
The above is the detailed content of Why Does My Go Web Server's Call Count Show Only Odd Numbers?. For more information, please follow other related articles on the PHP Chinese website!