I have used the below code to create a counter using cookies. But I guess there is an issue with this http.HandleFunc("/", foo)
function. Ideally the counter should be incremented only when the request is http:localhost:8080
or http:localhost:8080/
.
But the count
is getting incremented even if I type some random text after "/"
(ex: http:localhost:8080/abcd
).
func main() {
http.HandleFunc("/", foo)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func foo(res http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("my-cookie-counter")
if err == http.ErrNoCookie {
cookie = &http.Cookie{
Name: "my-cookie-counter",
Value: "0",
}
}
count, err := strconv.Atoi(cookie.Value)
if err != nil {
log.Fatalln(err)
}
count++
cookie.Value = strconv.Itoa(count)
http.SetCookie(res, cookie)
io.WriteString(res, cookie.Value)
}