This question already has an answer here:
I have this little server here. The intent is that if I visit localhost:8000/* it should increase counter
by 1, and if I go to localhost:8000/count, it should show me the current number of counter
.
A weird thing happening is that it seems like every time I visit localhost:8000
, the counter goes up by 3. So I'd go to localhost:8000/count
and the counter
would be at 3, and then I visit localhost:8000
, and then localhost:8000/count
again, counter
would now be at 6. Why does that happen? Is there something weird with net/http
?
Also, why is it that when I refresh localhost:8000/count
, the count goes up 1 by 1? The counter
func doesn't increment count
, yet count
still goes up - why is that? Does handler
get added to the localhost:8000/count
route as well?
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
var mu sync.Mutex
var count int
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path = %q
", r.URL.Path)
}
// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d
", count)
mu.Unlock()
}
</div>
The extra requests are your browser trying to access /favicon.ico
You can see this, for example, if you print the http.Request to stdout in your handler funcs.
The issue is that your handler is serving extra static content like favicon
and such. If you log the request, you'll see your browser is probably also requesting /favicon.ico, which is being passed to that same handler.
To serve static content one way is to create your own ServeMux:
package main
import (
"fmt"
"net/http"
"strings"
)
var chttp = http.NewServeMux()
func main() {
chttp.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", HomeHandler) // homepage
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if (strings.Contains(r.URL.Path, ".")) {
chttp.ServeHTTP(w, r)
} else {
fmt.Fprintf(w, "HomeHandler")
}
}