【发布时间】:2021-08-25 19:28:22
【问题描述】:
我正在尝试设置一个 Cookie,但有时它会起作用,而有时它却不起作用。没有明显的规律。
func quoteGetHandler(w http.ResponseWriter, req *http.Request) {
parts := strings.Split(req.URL.Path, "/")
csrfToken := uniuri.NewLen(32)
exp, err := strconv.Atoi(os.Getenv("COOKIE_EXPIRE")) //5
if err != nil {
http.Error(w, whereami.WhereAmI()+err.Error(), http.StatusInternalServerError)
}
expire := time.Now().Add(time.Duration(exp) * time.Minute)
cookie := http.Cookie{
Name: os.Getenv("COOKIE_NAME"), //csrf_token
Value: csrfToken, //string
Path: "/",
Expires: expire,
HttpOnly: true,
Secure: true,
MaxAge: 0,
Domain: os.Getenv("DOMAIN")} //<--example.com
http.SetCookie(w, &cookie)
tmp := htmlTags["quote"]
tmp.CsrfToken = csrfToken
if 2 < len(parts) && parts[2] != "" {
tmp.Param = parts[2]
}
htmlTags["quote"] = tmp
err = tmpl.ExecuteTemplate(w, siteType+"quote", htmlTags["quote"])
if err != nil {
http.Error(w, whereami.WhereAmI()+err.Error(), http.StatusInternalServerError)
}
}
这发生在 Chrome、FF、Bravo、Safari 上。
协议是https。
【问题讨论】:
-
与您的问题无关,但为什么您要为每个请求重新解析环境变量,而不是一次?
-
“有时有效,有时无效” - 什么是“有效”,什么是“无效”。您甚至观察到什么 - HTTP 响应、应用程序行为....?这种不稳定的行为与环境变量相同吗?
-
有时它会按预期设置 cookie。然后它不设置cookie。这种行为非常随机。