Session 在Gorilla会话中使用自定义类型
我试图使用Golang中的gorilla会话来存储会话数据。我发现我可以存储字符串的片段([]字符串),但不能存储自定义结构的片段([]自定义类型)。我想知道是否有人有这个问题,如果有任何修复它 我可以很好地运行会话,并获得其他变量,这些变量不是我存储的自定义结构的切片。我甚至能够将正确的变量传递给session.Values[“variable”],但当我执行session.Save(r,w)时,它似乎不会保存变量 编辑:找到解决方案。一旦我完全理解,我将进行编辑。解决了这个问题 您需要注册gob类型,以便会话可以使用它 例:Session 在Gorilla会话中使用自定义类型,session,go,Session,Go,我试图使用Golang中的gorilla会话来存储会话数据。我发现我可以存储字符串的片段([]字符串),但不能存储自定义结构的片段([]自定义类型)。我想知道是否有人有这个问题,如果有任何修复它 我可以很好地运行会话,并获得其他变量,这些变量不是我存储的自定义结构的切片。我甚至能够将正确的变量传递给session.Values[“variable”],但当我执行session.Save(r,w)时,它似乎不会保存变量 编辑:找到解决方案。一旦我完全理解,我将进行编辑。解决了这个问题 您需要注册g
我知道这个问题已经得到了回答。但是,有关会话中对象的设置和检索的参考,请参见下面的代码
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)
}
您可以通过以下方式访问:
->会话值设置->会话值检索
希望这有帮助 没有明确说明(但事后看来有意义)的是您必须已导出字段(即
type Person struct{Name…
vstype Person struct{Name
)否则序列化将不起作用,因为gob无法访问字段。请提交一个带有代码的答案。请更正延迟。代码已发布。好的,我使用gob.Register()
序列化了数据,但是否可以将会话中的数据存储到变量中?应该是什么类型?
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)
}