2014-07-18 30 views
3

我想在Golang中使用大猩猩會話來存儲會話數據。我發現我可以存儲字符串切片([]字符串),但我無法存儲自定義結構切片([] customtype)。我想知道是否有人有這個問題,如果有任何修復它。在大猩猩會話中使用自定義類型

我可以正常運行會話並獲取其他變量,而不是我已經存儲的自定義結構的切片。我甚至能夠將正確的變量傳遞給session.Values [「variable」],但是當我執行session.Save(r,w)時,它似乎不保存變量。

編輯:找到解決方案。一旦我充分理解,我會編輯。

+0

用代碼提交答案請 – OneOfOne

+0

對不起,延誤了。代碼發佈。 – Ben

回答

7

解決了這個問題。

您需要註冊採樣類型,以便會話可以使用它。

例:

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

我明白,這已經被回答。但是,有關在會話中設置和檢索對象的參考信息,請參閱下面的代碼。

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 - >會話值檢索

希望這有助於!