golang gorilla / session在检查会话时获得了nil值

时间:2015-04-08 11:07:47

标签: go gorilla

我已将软件包导入为

import (
    "github.com/gorilla/sessions"
    "github.com/gorilla/mux"

    //CORS
    "github.com/rs/cors"
    "github.com/justinas/alice"  
)

并定义了商店和主要方法如下

var store = sessions.NewCookieStore([]byte("something-very-secret")) 

const My_UI="http://localhost:3000"

func init() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
    }
}

var router = mux.NewRouter() //MUX Handeler

//MAIN Function

func main() {
    c := cors.New(cors.Options{
        AllowedOrigins: []string{My_UI},
    })

    router.HandleFunc("/submitted",Login)
    router.HandleFunc("/check",GetSession)
    http.Handle("/", router)

    chain := alice.New(c.Handler).Then(router) //CORS enable

    fmt.Println("server started at port 8080")
    http.ListenAndServe(":8080", chain)
}

在我的方法中,我创建并设置会话值,如gorilla doc

中所述
func Login(w http.ResponseWriter, r *http.Request) {         
    fmt.Println("In login----------->")
    sess := GetCon()                              //get connection session
    defer sess.Close()                           //close session    
    c := sess.DB("mydb").C("users")      //collection-> select db table

    session1, _ := store.Get(r, "loginSession")  //login session

    //parse json data  
    form := LoginUser{}
    err := json.NewDecoder(r.Body).Decode(&form)
    if err !=nil {
        fmt.Println(err)
    }

    //get query data
    var result []Person

    errc1 := c.Find(bson.M{"email":form.Email,"password":form.Password}).All(&result)

    if errc1 != nil {
        js, err2 := json.Marshal("false")
        if err2 != nil{return}
        w.Header().Set("Content-Type", "application/json")
        w.Write(js)     
    } else {
        if len(result)==0 {
            if err2 != nil {
                return
            }
            w.Header().Set("Content-Type", "application/json")
            w.Write(js) 
        } else {
            fmt.Println("Success")  
            session1.Values["foo"] = "bar"  
            session1.Save(r, w) 
            fmt.Println("saved",session1)
            js, err2 := json.Marshal(&result[0].Id)
            if err2 != nil {return}
            w.Header().Set("Content-Type", "application/json")
            w.Write(js) 
        }       
    }   
}

现在,如果我想在另一种方法中获得此会话值,我每次都会得到nil。我不知道我的代码出了什么问题。

func GetSession(w http.ResponseWriter, r *http.Request) {
    session1, _ := store.Get(r, "loginSession")
    fmt.Println("Session in SessionHandler",session1)

    if session.Values["foo"] == nil {
        fmt.Println("not found",session.Values["foo"]))
    } else {
        fmt.Println("value",session.Values["foo"])
    }
}

2 个答案:

答案 0 :(得分:2)

你的GetSession函数出错了。请将session变量更改为session1

同样要检查会话值是否更好,请按以下方式执行:

session, err := store.Get(r, ssid)
    if err == nil {
        if value, ok := session.Values["foo"].(string); ok {
            session_data = value
        }
    }

答案 1 :(得分:1)

我不知道你有什么价值,但我认为你想要一个字符串值。我写了简单的func GetFoo()来从session1.Values["foo"]获取字符串值。

以下完整示例:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "github.com/justinas/alice"
    "github.com/rs/cors"
)

var store = sessions.NewCookieStore([]byte("something-very-secret"))

const My_UI = "http://localhost:3000"

var router = mux.NewRouter() //MUX Handeler

//MAIN Function
func init() {
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
    }
}

func main() {
    c := cors.New(cors.Options{
        AllowedOrigins: []string{My_UI},
    })
    router.HandleFunc("/login", Login)
    router.HandleFunc("/check", GetSession)
    http.Handle("/", router)
    chain := alice.New(c.Handler).Then(router) //CORS enable
    fmt.Println("server started at port 8080")
    http.ListenAndServe(":8080", chain)
}

func GetFoo(f interface{}) string {
    if f != nil {
        if foo, ok := f.(string); ok {
            return foo
        }
    }
    return ""
}

func GetSession(w http.ResponseWriter, r *http.Request) {
    session1, _ := store.Get(r, "loginSession")
    foo := GetFoo(session1.Values["foo"])
    if foo == "" {
        fmt.Println("Foo is not set! Login to set value.")
    } else {
        fmt.Println("Foo Value:", foo, ".")
    }
}

func Login(w http.ResponseWriter, r *http.Request) {
    // Save Foo
    session1, _ := store.Get(r, "loginSession")
    session1.Values["foo"] = "bar"
    session1.Save(r, w)
}