Home >Backend Development >Golang >Why Does My Simple Go Web Server Show Only Even-Numbered Call Counts?
Why is this Simple Web Server Printed Even Times?
In this Go programming exercise, a simple web server is designed to count and display the number of times it has been called. However, upon refreshing the page, the printed values appear to increment only by even numbers (e.g., 1, 3, 5...).
Understanding the Order of Function Calls
Every incoming HTTP request triggers a call to the specified handler function (HelloWorld in this case). However, under the hood, the browser makes additional requests for resources, including /favicon.ico.
Since the server is not programmed to respond appropriately to the favicon request, the browser continues to request it upon each page refresh. This additional request increments the call counter by one.
Adjusting the Counter Logic
To correctly count the number of page refreshes, the server needs to disregard these additional requests. One solution is to only increment the counter when the request path is the root ("/").
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) }
Alternatively, the server can exclude requests specifically for favicon.ico.
func HelloWorld(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/favicon.ico" { return } count := atomic.AddInt64(&calls, 1) fmt.Fprintf(w, "You've called me %d times", count) }
The above is the detailed content of Why Does My Simple Go Web Server Show Only Even-Numbered Call Counts?. For more information, please follow other related articles on the PHP Chinese website!