【问题标题】:Using custom types with Gorilla sessions在 Gorilla 会话中使用自定义类型
【发布时间】:2018-07-29 21:22:48
【问题描述】:

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

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

编辑:找到解决方案。等我完全理解后再编辑。

【问题讨论】:

  • 请用代码提交答案
  • 抱歉耽搁了。代码已发布。

标签: session go


【解决方案1】:

解决了这个问题。

您需要注册 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)
}

【讨论】:

    【解决方案2】:

    没有明确说明(但事后看来是有道理的)是​​您必须已导出字段(即type Person struct { Name ... vs type Person struct { name)否则序列化将无法工作,因为 gob 不能访问字段。

    【讨论】:

      【解决方案3】:

      我知道这个问题已经得到解答。但是,作为在会话中设置和检索对象的参考目的,请参见下面的代码。

      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 -> 会话值检索

      希望这会有所帮助!

      【讨论】:

      • 好的,我使用gob.Register() 序列化了数据,但是可以将数据从会话存储到变量吗?应该是什么类型的?
      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2012-10-27
      • 2021-04-09
      • 2014-11-30
      • 2014-03-18
      • 2019-01-31
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多