【问题标题】:Go : How to Set same Cookie on all pages?Go : 如何在所有页面上设置相同的 Cookie?
【发布时间】:2013-06-21 06:04:11
【问题描述】:

登录后,我的 url 更改为 /login/ 并设置了 cookie。 设置cookie后需要重定向主页上的页面(url:/homePage/)而不是/login/。

如何在所有页面中设置相同的cookie?

【问题讨论】:

  • 我发现使用像 Gorilla Sessions 这样的东西真的可以帮助解决这个问题 (gorillatoolkit.org/pkg/sessions)
  • 与 go-google-app-engine ?
  • 我已经使用 Gorilla 网络工具包推荐的 GAE 设置编辑了我的答案。

标签: google-app-engine session cookies go session-cookies


【解决方案1】:

您可以使用内置的 CookieJar 库来管理 cookie 存储(请参阅 this 答案以获取一些指示),但使用 Gorilla Web Toolkit 中的 Gorilla Sessions 可能更容易。

还有一些 GAE 特定设置(来自http://www.gorillatoolkit.org/):

对于 Google App Engine,在您的应用内创建一个目录树并在其中克隆存储库:

$ cd myapp
$ mkdir -p github.com/gorilla
$ cd github.com/gorilla
$ git clone git://github.com/gorilla/mux.git

该示例的最后一行特定于 mux 包。您可以将其替换为:

git clone git://github.com/gorilla/sessions.git

一个简单的例子:

定义您的 cookie 存储:

import (
    "github.com/gorilla/sessions"
    "net/http"
)

// Authorization Key
var authKey = []byte{
    0x70, 0x23, 0xbd, 0xcb, 0x3a, 0xfd, 0x73, 0x48,
    0x46, 0x1c, 0x06, 0xcd, 0x81, 0xfd, 0x38, 0xeb,
    0xfd, 0xa8, 0xfb, 0xba, 0x90, 0x4f, 0x8e, 0x3e,
    0xa9, 0xb5, 0x43, 0xf6, 0x54, 0x5d, 0xa1, 0xf2,
}

// Encryption Key
var encKey = []byte{
    0x31, 0x98, 0x3E, 0x1B, 0x00, 0x67, 0x62, 0x86,
    0xB1, 0x7B, 0x60, 0x01, 0xAA, 0xA8, 0x76, 0x44,
    0x00, 0xEB, 0x56, 0x04, 0x26, 0x9B, 0x5A, 0x57,
    0x29, 0x72, 0xA1, 0x62, 0x5B, 0x8C, 0xE9, 0xA1,
}

var store = sessions.NewCookieStore(authKey, encKey)

func initSession(r *http.Request) *sessions.Session {
    session, _ := store.Get(r, "my_cookie")
    if session.IsNew {
        session.Options.Domain = "example.org"
        session.Options.MaxAge = 0
        session.Options.HttpOnly = false
        session.Options.Secure = true
    }
    return session
}

然后,在您的页面处理程序中,您只需加载 cookie,设置您喜欢的任何选项并重新保存它:

func ViewPageHandler(w http.ResponseWriter, r *http.Request) {
    session := initSession(r)
    session.Values["page"] = "view"
    session.Save(r, w)
....

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2011-10-27
    • 1970-01-01
    相关资源
    最近更新 更多