在Gorilla会话中使用自定义类型

biw*_*biw 4 session go

我试图在Golang中使用gorilla会话来存储会话数据.我发现我可以存储一些字符串([]字符串),但我不能存储自定义结构的片段([] customtype).我想知道是否有人有这个问题,是否有任何修复.

我可以运行会话,并获得其他变量,这些变量不是我存储的自定义结构的片段.我甚至能够将正确的变量传递给session.Values ["variable"],但是当我执行session.Save(r,w)时,它似乎没有保存变量.

编辑:找到解决方案.一旦我完全理解,将编辑.

biw*_*biw 9

解决了这个问题.

您需要注册gob类型,以便会话可以使用它.

例如:

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", "Bob@Smith.com", 22}

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

   //save the session
   session.Save(r, w)
}
Run Code Online (Sandbox Code Playgroud)