设置未检测到Cookie

I'm running into a problem trying to retrieve a cookie if it is set and if not I want to update it then retrieve it.

To start I have a function that sets a cookie:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ck := http.Cookie{
        Name: "id",
        Value: 5,
        MaxAge: 60,
    }
}

Then in another function I check to see if that cookie exists and if it (throws an error) then I recreate it

func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        ck := http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }

        http.SetCookie(w, &ck)
        CheckUpdateCookie(w, r)
    }
}

This leads to it running into an infinite loop and not recognizing that the cookie has been set again, if I print the err I get http: named cookie not present even though I have set the cookie in the body of the function.

The call to r.Cookie("id") reads a "Cookie" header in the request.

The call to http.SetCookie(w, &ck) adds a "Set-Cookie" header in the response. The call does not modify the request.

Instead of calling the function recursively to get the cookie (which does not work for the reasons stated above), just use the cookie you have on hand:

func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }
        http.SetCookie(w, val)
    }
    // val is now set to the cookie.
}

It is typical to set the path to "/" so that the cookie is available on all paths:

        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
            Path: "/",
        }