使用Gorilla sessions与自定义类型

huangapple go评论94阅读模式
英文:

Using custom types with Gorilla sessions

问题

我正在尝试使用Golang中的gorilla sessions来存储会话数据。我发现我可以存储字符串切片([]strings),但无法存储自定义结构体的切片([]customtype)。我想知道是否有人遇到过这个问题,以及是否有任何解决方法。

我可以正常运行会话,并且可以正常获取存储的不是自定义结构体切片的其他变量。我甚至可以将正确的变量传递给session.Values["variable"],但是当我执行session.Save(r, w)时,似乎无法保存该变量。

编辑:找到了解决方案。一旦我完全理解了,我会进行编辑。

英文:

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.

答案1

得分: 12

解决了这个问题。

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

示例代码如下:

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

type Person struct {
    FirstName string
    LastName  string
    Email     string
    Age       int
}

func main() {
    // 现在我们可以在会话中使用它
    gob.Register(Person{})
}

func createSession(w http.ResponseWriter, r *http.Request) {
    // 创建会话
    session, _ := store.Get(r, "Scholar0")

    // 创建新的结构体
    x := Person{"Bob", "Smith", "Bob@Smith.com", 22}

    // 添加值
    session.Values["User"] = x

    // 保存会话
    session.Save(r, w)
}
英文:

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", "Bob@Smith.com", 22}
   
   //add the value
   session.Values["User"] = x
   
   //save the session
   session.Save(r, w)
}

答案2

得分: 1

事后看来是不明确说明的(但是有意义的)是,你必须有导出字段(即 type Person struct { Name ... vs type Person struct { name),否则序列化将无法正常工作,因为 gob 无法访问这些字段。

英文:

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.

答案3

得分: 0

我明白这个问题已经有答案了。然而,为了参考设置和检索会话中的对象的目的,请参考下面的代码。

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

你可以通过以下方式访问它:

http://localhost:8080/1 -> 设置会话值
http://localhost:8080/2 -> 检索会话值

希望这可以帮到你!

英文:

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<br/>
http://localhost:8080/2 -> session value retrieval
<br/><br/>
Hope this helps!

huangapple
  • 本文由 发表于 2014年7月19日 06:04:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/24834480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定