Visit-counting cookie counts twice at once

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 (

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")
		c.Value = strconv.Itoa(cin)
		http.SetCookie(w, c)
	tpl, _ := template.ParseFiles("index.html")
	tpl.Execute(w, "aaa")

Check the request Method. You may be getting requests other than GET.

Handle “/” is treated like a directory and will handle ALL requests, which are not matched by any other handler. Just like handle(“/api/”) will also handle requests to “/api/foobar”

If you open the DevTools of your browser and the Network-Tab you will see all requests to your server. Most browsers will search for a favicon (the little icon which is different on the browser tab for each page) and make a silent call to “/favicon.ico” in the background. This call will be received by your “/” handler.

You can debug this by adding a fmt.Printf(“%+v\n”, r) to your handler, the placeholder “%+v” will print all details of the request object and you can see what path was called.

1 Like