Hi, I’m studying about web development and cookies.
In my code, the visit-counting cookie works well when I access in ‘localhost:8084/abc’.
It counts the number of visiting one by one.
BUT when I access to default path(“/”), the cookie counts the visiting time twice at the same time.
anyone knows about this problem and how to solve it?
package main
import (
"fmt"
"net/http"
"strconv"
"text/template"
)
func main() {
http.HandleFunc("/", ab)
http.HandleFunc("/abc", abc)
http.ListenAndServe(":8084", nil)
}
func abc(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("VisitNum")
if err != nil {
fmt.Fprint(w, err, " 1")
}
tpl, err := template.ParseFiles("index2.html")
if err != nil {
fmt.Fprint(w, err, " 2")
}
tpl.Execute(w, c.Value)
}
func ab(w http.ResponseWriter, r *http.Request) {
c, _ := r.Cookie("VisitNum")
if c == nil {
c := &http.Cookie{
Name: "VisitNum",
Value: "1",
}
http.SetCookie(w, c)
} else {
cin, err := strconv.Atoi(c.Value)
if err != nil {
fmt.Fprint(w, err, " 4")
}
cin++
c.Value = strconv.Itoa(cin)
http.SetCookie(w, c)
}
tpl, _ := template.ParseFiles("index.html")
tpl.Execute(w, "aaa")
}