Home > Backend Development > Golang > Why is my Go `HandleFunc` called twice when using a web browser?

Why is my Go `HandleFunc` called twice when using a web browser?

Mary-Kate Olsen
Release: 2024-12-15 08:21:18
Original
247 people have browsed it

Why is my Go `HandleFunc` called twice when using a web browser?

Unexpected Double Invocation of HttpHandler: HandleFunc

Introduction

When utilizing the http.ServeMux multiplexer in a Go web server, it's observed that a registered handler function (HandleFunc) is invoked twice for each request made from a web browser. This behavior is contrary to the intended functionality.

Problem

Upon implementing a basic web server with a handler function that increments a counter, it's observed that the counter is incremented twice for each browser request. However, when using curl, the handler is invoked only once as expected.

Cause

After logging the requests, it becomes evident that the browser also sends a request for /favicon.ico. This is a request for a small icon that is typically displayed in the browser's address bar or tab. As the ServeMux multiplexer matches all URLs by default, it invokes the registered handler for this additional request, resulting in the double invocation.

Solution

To prevent the handler from being invoked for the favicon.ico request, two approaches can be considered:

  1. Add a Specific favicon.ico Handler:

    func favicon(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "favicon.ico")
    }
    
    func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", hello)
    mux.HandleFunc("/favicon.ico", favicon)
    http.ListenAndServe(":8000", mux)
    }
    Copy after login

By defining a separate handler for /favicon.ico, the hello handler will only be invoked for regular page requests.

  1. Skip the Handler for Default Patterns:

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
        hello(w, r)
    }
    })
    Copy after login

This approach checks the URL.Path of the request and ensures the hello handler is invoked only when the path is exactly /.

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