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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With