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.
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.
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:
// 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.
// HandleFunc registers the handler function for the given pattern // in the DefaultServeMux.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With