Update: The question title can be misleading. This was not Go's fault at all.
See the first comment or the accepted answer.
This following code (well, almost the same) counts page views under Linux allright, but counts them double under Windows.
Can someone figure out why?
package main
import (
"fmt"
"http"
)
func main() {
println("Running")
http.HandleFunc("/", makeHomeHandler())
http.ListenAndServe(":8080", nil)
}
// this version compiles and run OK under the Linux version of Golang
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
views := 1
return func(c *http.Conn, r *http.Request) {
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
views++
}
}
/*
// this version compiles and run OK under the mingw version of Golang
// it uses a different argument type for the handler function,
// but the counter says "1 so far", then "3 so far", "5 so far", and so on.
func makeHomeHandler() func(c http.ResponseWriter, r *http.Request) {
views := 1
return func(c http.ResponseWriter, r *http.Request) {
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
views++
}
}
*/
Under Mingw:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 3 so far.
http://localhost:8080/donkeys => Counting donkeys, 5 so far.
Could this be a bug?
Followup:
In fact, if I define an additional handler for another page, like:
http.HandleFunc("/test", testPageHandler)
Wich does not have a closure, nor increments anything, the counter gets incremented anyway, but only +1:
So, still under Mingw:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 3 so far.
http://localhost:8080/test => Another handler function that does not increment "views"
http://localhost:8080/donkeys => Counting donkeys, 6 so far.
Under Linux output is as spected:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 2 so far.
http://localhost:8080/test => Another handler function that does not increment "views"
http://localhost:8080/donkeys => Counting donkeys, 3 so far.