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

golang gorilla/session在检查会话时获得了nil值,go,gorilla,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_U

我进口了一些包装

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文档中描述的会话值

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

我不知道你要得到什么值,但我假设你想要一个字符串值。我编写了简单的
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)
}

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

另外,要检查会话值是否存在,请按以下方式执行:

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

你检查错误了吗?看起来您在示例代码中忽略了它们。如果让我猜的话,我会说您在保存会话(发送的标题)之前已经写入了http.ResponseWriter。是的,我已经检查过了。在GetSession()方法中检查会话条件时,获得了nil值->“未找到”。根据doc(gorilla)关于保存任何会话的说明,我们必须编写会话。保存(r,w)。。对于多个会话,他们会提到sessions.Save(r,w)。正确-但在呈现模板或编写任何类型的响应之前,您需要这样做。能否在代码中发布完整的
登录
功能?渲染与此无关。如果您在设置标头(cookie将在此处设置)之前在HTTP正文中进行输出,那么它将不起作用。