This question already has an answer here:
- Why this simple web server is called even number times? 1 answer
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\n", 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\n", count)
mu.Unlock()
}