Gorilla/sessions Study Notes

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Simple examples

    • First Call Newcookiestore to initialize a store and pass in a secret key to authenticate the session.
    • In Handler , call store. Get () gets a session that already exists or (if it does not exist) creates a new one.
    • Set the sesssion. value in values, session. Values are map[interface{}]interface{} types.
    • Call session. Save () saves the session to the response.

      In the actual project, the session is called. Save (R,W) needs to detect the returned error and handle it.
      The Save () method must be called before writing to response, or the session cookie will not be sent to the client.

var store = sessions. Newcookiestore ([]byte ("Something-very-secret")) func MyHandler (w http. Responsewriter, R *http. Request) {session, Err: = store. Get (R, "S1") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} FMT. PRINTLN (session) session. values["name"] = "Kingeastensun" session. Save (R, W)}func Multisessionhandler (w http. Responsewriter, R *http. Request) {session1, err: = store. Get (R, "S1") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} FMT. Println (Session1) session1. values["name"] = "Kingeastensun" Session2, err: = store. Get (R, "S2") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} FMT. Println (Session2) session2. values["name"] = "Kingeastensunyx" sessions. Save (R, W)}func main () {routes: = Mux. Newrouter () routes. Handlefunc ("/session", MyHandler) routes. Handlefunc ("/musession", MulTisessionhandler) http. Handle ("/", routes) HTTP. Listenandserve (": 8080", nil)}

Multi-session Processing

See Multisessionhandler, when saving, call

sessions.Save(r, w)

You can save Session1 and session2 at the same time.

Complex structural data

Type Mperson struct {FirstName string LastName string e-mail string age Int}type M Map[string]inter Face{}func init () {FMT. Println ("Init") gob. Register (&mperson{}) gob. Register (&m{})}var store = sessions. Newcookiestore ([]byte ("Something-very-secret")) Func Setmhandler (w http. Responsewriter, R *http. Request) {session, Err: = store. Get (R, "M") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} MS: = Mperson{firstname: "King", LastName: "Eastersun"} session. Values["MS"] = ms M: = Make (map[string]interface{}) m["name"] = "Kingeasternsun" session. values["M"] = m err = session. Save (R, W) if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return}}func Getmhandler (w http. Responsewriter, R *http. Request) {session, Err: = store. Get (R, "M") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} MS: = Session. Values["MS"]//var person = &mperson{} if person, OK: = Ms. (*mperson); OK {fmt. PRINTLN (person)} else {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} m: = Session. values[' m ']//var mmap = m{} if mmap, OK: = M. (*m); OK {fmt. Println (mmap)} else {http. Error (W, err. Error (), HTTP. STATUSINTERNALSERVERERROR) return}}func main () {//FMT. Println (String (Securecookie. Generaterandomkey (+))//FMT. Println (String (Securecookie. Generaterandomkey (+)) Routes: = Mux. Newrouter () routes. Handlefunc ("/setm", Setmhandler) routes. Handlefunc ("/getm", Getmhandler) http. Handle ("/", routes) HTTP. Listenandserve (": 8080", nil)}

Error when setting


Browser error

The problem is

    m := make(map[string]interface{})    m["name"] = "kingeasternsun"

map[string]interface{} is not registered to the session, only Mpersion and M are registered in Init, although M is defined in the following way:

type M map[string]interface{}

But in Golang, this way of declaring, M and map[string]interface{} belong to different types.
Modify the Setmhandler as follows:

func SetMHandler(w http.ResponseWriter, r *http.Request) {    session, err := store.Get(r, "m")    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }    ms := MPerson{FirstName: "king", LastName: "eastersun"}    session.Values["ms"] = ms    m := M{}    m = make(map[string]interface{})    m["name"] = "kingeasternsun"    session.Values["m"] = m    err = session.Save(r, w)    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }}

Cookie Set Success


Cookie Set Success

Failed to get cookie

Double quotes are mistakenly written in the code as single quotes

    m := session.Values['m']    m := session.Values["m"]

Get Cookie Success

Replacement of key

In the project you may encounter the need to replace key, sessions can also be easily implemented

var store = sessions.NewCookieStore(    []byte("new-authentication-key"),    []byte("new-encryption-key"),    []byte("old-authentication-key"),    []byte("old-encryption-key"),)

Store through this method of creation, the new sessions will be created by a key pair, while the old sessions is read by the old key pair.

For all key pair, encryption key is optional, and if empty or omitted, it is not good to encrypt.

Postscript

has been in the csdn to write articles, the latter will be gradually converted to the book, but also ask you to support a lot.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.