Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using custom types with Gorilla sessions

Tags:

session

go

I am trying to use gorilla sessions in Golang to store session data. I have found that I can store slices of strings ([]strings) but I cannot store slices of custom structs ([]customtype). I was wondering if anyone had this problem and if there was any fix for it.

I can run sessions fine and get other variables that are not slices of custom structs I have stored fine. I even am able to pass the correct variables to session.Values["variable"] but when I do session.Save(r, w) it seems to not save the variable.

EDIT: Found the solution. Will edit once I get full understanding.

like image 690
biw Avatar asked Jul 18 '14 22:07

biw


1 Answers

Solved this one.

You need to register the gob type so that sessions can use it.

Ex:

import(
"encoding/gob"
"github.com/gorilla/sessions"
)

type Person struct {

FirstName    string
LastName     string
Email        string
Age            int
}

func main() {
   //now we can use it in the session
   gob.Register(Person{})
}

func createSession(w http.ResponseWriter, r *http.Request) {
   //create the session
   session, _ := store.Get(r, "Scholar0")

   //make the new struct
   x := Person{"Bob", "Smith", "[email protected]", 22}

   //add the value
   session.Values["User"] = x

   //save the session
   session.Save(r, w)
}
like image 177
biw Avatar answered Nov 15 '22 10:11

biw