biw
biw

Reputation: 3085

Using custom types with Gorilla sessions

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.

Upvotes: 5

Views: 2755

Answers (3)

Andrew M
Andrew M

Reputation: 11

What is not explicitly stated (but makes sense in hindsight) is that you must have exported fields (i.e type Person struct { Name ... vs type Person struct { name) otherwise serialisation won't work as gob can't access the fields.

Upvotes: 1

Kent Aguilar
Kent Aguilar

Reputation: 5338

I understand that this has been answered already. However, for reference purposes on the setup and retrieval of an object in a session, please see below code.

package main

import (
    "encoding/gob"
    "fmt"
    "net/http"
    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

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

type Person struct {
    FirstName string
    LastName string
}

func createSession(w http.ResponseWriter, r *http.Request) {    
    gob.Register(Person{})

    session, _ := store.Get(r, "session-name")

    session.Values["person"] = Person{"Pogi", "Points"}
    session.Save(r, w)

    fmt.Println("Session initiated")
}

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

func main() {
    http.HandleFunc("/1", createSession)
    http.HandleFunc("/2", getSession)

    http.ListenAndServe(":8080", nil)
}

You can access this via:

http://localhost:8080/1 -> session value setup
http://localhost:8080/2 -> session value retrieval

Hope this helps!

Upvotes: 0

biw
biw

Reputation: 3085

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)
}

Upvotes: 12

Related Questions