Home >Backend Development >Golang >Why is my Go HTTP function handler called twice?

Why is my Go HTTP function handler called twice?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 09:27:14507browse

Why is my Go HTTP function handler called twice?

HTTP Function Handler Called Unexpectedly

When using HTTP handlers in Go, it's crucial to understand how requests are processed. In a common scenario, a browser not only makes a request to the root URL but also requests an icon file named "/favicon.ico" for visual purposes. This additional request can lead to a handler function being called twice.

Example:

Consider the following code that increments a counter on each page visit:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

var counter int

func hello(w http.ResponseWriter, r *http.Request) {
    counter++
    io.WriteString(w, fmt.Sprintf("Hello world! Counter: %d", counter))
    log.Println("hello.")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", hello)
    http.ListenAndServe(":8000", mux)
}

Observation:

If you access port 8000 in a web browser, you'll notice that the "hello" handler is called twice. This is because the browser also makes a request for "/favicon.ico." If you use cURL to access the same URL, the handler is only called once.

To understand and resolve this issue, simply log the requests. You'll see that the second request is for "/favicon.ico." To avoid this, you can either:

  • Create a handler specifically for "/favicon.ico" and serve a placeholder icon or favicon.
  • Configure your HTTP server to ignore "/favicon.ico" requests.

Understanding the HTTP request flow and considering specific edge cases will help you write robust and reliable web servers with Go.

The above is the detailed content of Why is my Go HTTP function handler called twice?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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