Go : How to Set same Cookie on all pages?

雨燕双飞 提交于 2019-12-25 11:53:04

问题


After logging in my url changes to /login/ and cookie gets set. After setting cookie need to redirect the page on home page (url : /homePage/) other than /login/.

How to set same cookie in all pages?


回答1:


You can use the inbuilt CookieJar library to manage a store of cookies (see this answer for some pointers), but it's probably easier to use something like Gorilla Sessions from the Gorilla Web Toolkit.

There is also some GAE specific setup (from http://www.gorillatoolkit.org/):

For Google App Engine, create a directory tree inside your app and clone the repository there:

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

The last line of that example is specific to the mux package. You would replace it with:

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

A quick example:

Define your cookie store:

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
}

And then, in your page handlers you just load the cookie, set any options you like and re-save it:

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

Hope that helps.



来源:https://stackoverflow.com/questions/17228655/go-how-to-set-same-cookie-on-all-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!