Gorilla 会话包混淆

Gorilla session package confusion

来自 PHP 背景,我对 Gorilla 会话包有点困惑。

大猩猩的行为与 $_SESSION['name'] 相似,还是与 PHP 的 $_COOKIE['name'] 相似?

我正在尝试使用这两种方法为我的 Go Web 应用程序创建用户会话,但我不确定 Gorilla 会话是否是一个很好的包。我希望那些没有点击登录表单上的 "remember me" 按钮的用户在关闭浏览器后删除他们的会话,而其他人都会有一个与他们相关联的 cookie。那么 Gorilla 会话是否能够处理这两种情况,或者在这种情况下我应该使用其他方法吗?

这完全取决于您使用的存储后端。

gorilla/sessions 包有内置的 cookie 和基于文件系统的商店。没有基于内存的存储,这与 PHP 的 $_SESSION 大致相同。

我的推荐:

  • 使用内置的 cookie 存储,它使用签名的 cookie。它非常适合大多数用途,也是最容易实现的。
  • 如果您需要服务器端会话(即在会话中存储大值),pick from the available implementations - Redis、BoltDB、mySQL、Postgres 等

我对 Redis 支持的存储 (redistore) 有第一手经验,这很棒。如果您偏爱 BoltDB(基于文件的密钥存储)和 Postgres 存储,它们也很可靠。

I want the users who didn't click on the "remember me" button on the login form to have their session erased after closing their browser, whereas everyone else will have a cookie associated with them. So would Gorilla sessions be able to handle both scenarios or should I use something else in this case?

请注意,所有实现都需要一个 "cookie" - 这只是 cookie 是否是独立存储,或者它是否仅包含一个指向后端存储中的 row/value 的标识符.

您可以根据 this part of the gorilla/sessions docs.

设置 session.Options.MaxAge = 0 来设置 "session cookies"(即仅持续 tab/browser 会话)

例如

func MyHandler(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    // Add your logic to check the r.FormValue for your remember_me checkbox.

    // Temporary session
    session.Options.MaxAge = 0

    // Set some session values.
    session.Values["user"] = someUser
    // Save it before we write to the response/return from the handler.
    session.Save(r, w)
}

希望对您有所帮助。