Issue When Saving Structs in Session

245 views
Skip to first unread message

Ji Park

unread,
Dec 31, 2013, 1:33:22 AM12/31/13
to goril...@googlegroups.com
Hello there, I'm trying to save structs in session in one handler and retrieve them from another handler, but I keep seeing nil instead of the structs.


As you can see, when I go to localhost:8080/1, MyHandler1 sets values for the two structs and saves them to the session, and then I expect to have the structs be printed out when I access localhost:8080/2.

I'd really appreciate your help,

Thank you!

Srinath

unread,
Dec 31, 2013, 2:05:11 AM12/31/13
to goril...@googlegroups.com
Well, session.Save will return error. you can get info on the error by printing or acting on it. 

There was an error saying <gob: type main.Person has no exported fields>.
So, I changed both Person & Monster to what it looks in the following. Just make sure the required fields are exported so that gob can access the fields which you need to save in session.

package main

import (
"encoding/gob"
"fmt"
"net/http"

)

var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32))

func main() {
sessions.NewSession(store, "session-name")
http.HandleFunc("/1", MyHandler1)
http.HandleFunc("/2", MyHandler2)
http.ListenAndServe(":8080", nil)
}

type Person struct {
Name string
}

type Monster struct {
Name string
}

func init() {
gob.Register(&Person{})
gob.Register(&Monster{})
}

func MyHandler1(w http.ResponseWriter, r *http.Request) {

session, _ := store.Get(r, "session-name")
session.Values["person"] = &Person{"John Doe"}
session.Values["monster"] = &Monster{"Sasquatch"}
fmt.Println(session.Save(r, w))
}

func MyHandler2(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
fmt.Println(session.Values["person"])
fmt.Println(session.Values["monster"])
}


http://about.me/srinathgs
I write code @ Alamut
Srinath G S



--
You received this message because you are subscribed to the Google Groups "Gorilla web toolkit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gorilla-web...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Ji Park

unread,
Dec 31, 2013, 2:14:04 AM12/31/13
to goril...@googlegroups.com
Thank you for the reply, I was able to fix the issue.

Matt Silverlock

unread,
Dec 31, 2013, 9:04:25 PM12/31/13
to goril...@googlegroups.com
Some extra notes:

- Export your struct fields if you want to change them (this means capitalizing the name of the field) from outside your package.
- Check the error from session.Get else you not be able to retrieve it
- Same goes for session.Save

Don't ignore errors ;)

Reply all
Reply to author
Forward
0 new messages