我在尝试检索 cookie(如果已设置)时遇到问题,如果未设置,我想更新它然后检索它。
首先,我有一个设置 cookie 的函数:
func IndexHandler(w http.ResponseWriter, r *http.Request) {
...
ck := http.Cookie{
Name: "id",
Value: 5,
MaxAge: 60,
}
}
Run Code Online (Sandbox Code Playgroud)
然后在另一个函数中,我检查该 cookie 是否存在,如果存在(抛出错误),则重新创建它
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)
}
}
Run Code Online (Sandbox Code Playgroud)
这会导致它陷入无限循环,并且无法识别 cookie 已被再次设置,如果我打印错误,http: named cookie not present即使我已经在函数体中设置了 cookie,我也会得到这个错误。
调用r.Cookie("id")读取请求中的“Cookie”标头。
调用会http.SetCookie(w, &ck)在响应中添加“Set-Cookie”标头。该调用不会修改请求。
不要递归调用该函数来获取 cookie(由于上述原因这不起作用),只需使用您手头的 cookie:
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.
}
Run Code Online (Sandbox Code Playgroud)
通常将路径设置为“/”,以便 cookie 在所有路径上都可用:
val := &http.Cookie{
Name: "id",
Value: 5,
MaxAge: 60,
Path: "/",
}
Run Code Online (Sandbox Code Playgroud)