Home > Backend Development > Golang > Why Does My Go Web Server's Call Count Show Only Odd Numbers?

Why Does My Go Web Server's Call Count Show Only Odd Numbers?

Linda Hamilton
Release: 2024-12-23 04:31:10
Original
508 people have browsed it

Why Does My Go Web Server's Call Count Show Only Odd Numbers?

Why a Web Server's Call Count Skips Even Numbers

Problem

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)
}
Copy after login

Solution

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template