Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HandleFunc being called twice

Tags:

go

I am following a simple web server example in Go.

I inserted a log statement so that the resulting code looks like below:

package main

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

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

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

Problem is that whenever I load port 8000 in my web browser, this function is called twice. This is an issue because I intend to increment a counter on each page visit. With this behavior, counter gets incremented twice. OTOH, if I do curl localhost:8000, it is called only once.

I feel it's something really silly that I am missing here.

like image 214
Dharmit Avatar asked Oct 30 '15 09:10

Dharmit


People also ask

What does the call to handlefunc () function do?

For example: Now, let’s look at what the call to HandleFunc () function does: // HandleFunc registers the handler function for the given pattern // in the DefaultServeMux.

What is handlefunc () in Java?

It can feel cumbersome to define a type implementing the Handler interface for every path we want to register a handler for. Hence, a convenience function, HandleFunc () is provided to register any function which has a specified signature as a Handler function. For example:

What is handlefunc in servemux?

// HandleFunc registers the handler function for the given pattern // in the DefaultServeMux. // The documentation for ServeMux explains how patterns are matched. func HandleFunc (pattern string, handler func (ResponseWriter, *Request)) { DefaultServeMux.

What does handlefunc Register in defaultservemux?

// HandleFunc registers the handler function for the given pattern // in the DefaultServeMux.


1 Answers

If you request from a service is fine, but if you test from a browser and is not the production intention you can do this in golang code for avoid browser load the favicon:

http.HandleFunc("/favicon.ico", doNothing)

And the function

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

For people voting negatives: this works, sorry for handle it with this code in an api that doesn't need favicon or whatever...

like image 196
Santiago Avatar answered Oct 18 '22 08:10

Santiago