You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go chi框架登录接口Cookie设置不生效问题求助

我在服务器的登录处理函数中设置了Cookie,但Cookie始终无法生效。

我的CORS配置

r := chi.NewRouter()

r.Use(cors.Handler(cors.Options{
    AllowedOrigins:   []string{"https://SECRET.COM", "http://SECRET.COM"},
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"*"},
    ExposedHeaders:   []string{"*"},
    AllowCredentials: true,
    MaxAge:           600, // Maximum value not ignored by any of major browsers
}))

登录处理函数

func (h *Handler) signIn(w http.ResponseWriter, r *http.Request) {
  var input signInInput

  err := json.NewDecoder(r.Body).Decode(&input)
  if err != nil {
    NewErrorResponse(w, http.StatusBadRequest, err.Error())
    return
  }

  token, err := h.Service.Authorization.GenerateToken(input.Email, input.Password)
  if err != nil {
    NewErrorResponse(w, http.StatusBadRequest, err.Error())
    return
  }

  http.SetCookie(w, &http.Cookie{
    Name:     JwtTokenName,
    Domain: "SECRET.COM",
    Value:    token,
    HttpOnly: false, // true - for prod; now it's false for test
    Expires:  time.Now().Add(6 * time.Hour),
    // MaxAge: 0, // TEST! WARNING
    Path:     "/",
  })

  w.WriteHeader(http.StatusOK)
  logger.Debug(fmt.Sprintf("User is logged in with email: %s.   Token: %s", input.Email, token))
}

我尝试了多种SetCookie的参数配置,但都没有效果:


http.SetCookie(w, &http.Cookie{
    Name:     JwtTokenName,
    Domain: "SECRET.COM",
    Value:    token,
    HttpOnly: false, // true - for prod; now it's false for test
    Expires:  time.Now().Add(6 * time.Hour),
    Path:     "/",
})

http.SetCookie(w, &http.Cookie{
    Name:     JwtTokenName,
    Value:    token,
    HttpOnly: false, 
    Expires:  time.Now().Add(6 * time.Hour),
    Path:     "/",
})

http.SetCookie(w, &http.Cookie{
    Name:     JwtTokenName,
    Domain: "SECRET.COM",
    Value:    token,
    HttpOnly: false,
    MaxAge: 0,
    Path:     "/",
})

http.SetCookie(w, &http.Cookie{
    Name:     JwtTokenName,
    Domain: "SECRET.COM",
    Value:    token,
    Path:     "/",
})

补充说明:问题与时间无关(我已预留足够余量,并考虑了服务器时区和时差)

内容的提问来源于stack exchange,提问作者Imran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:33:14