Home >Backend Development >Golang >Why is my Go HandleFunc invoked twice when accessed via a web browser?

Why is my Go HandleFunc invoked twice when accessed via a web browser?

DDD
DDDOriginal
2024-12-17 07:55:25240browse

Why is my Go HandleFunc invoked twice when accessed via a web browser?

HandleFunc Invoked Twice

In a simple Go web server example, a puzzling issue arises where the HandleFunc is called twice when accessing port 8000 through a web browser. This differs from the expected behavior when using curl, which triggers only a single invocation.

Unveiling the Issue

Upon implementing a logging statement to troubleshoot the problem, it becomes apparent that an additional request is made by the browser for /favicon.ico. This icon is typically displayed in the address bar of the browser.

Resolution

To resolve this mismatch in request processing, simply acknowledge the request for /favicon.ico in the HandleFunc. If no action is necessary for this specific request, a default empty response can suffice.

Here's the modified code:

package main

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

func hello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world!")
    log.Println("hello.")
}

func favicon(w http.ResponseWriter, r *http.Request) {
    http.NotFound(w, r)
}

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

The above is the detailed content of Why is my Go HandleFunc invoked twice when accessed via a web browser?. 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