golang gorilla/session 在检查会话时得到了空值。

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

golang gorilla/session got nil value while checking session

问题

我已经导入了以下包:

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

I have imported packages as

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

and defined store and main method as follow

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

In my method I’ve created and set session value as describe in 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)	
}		
}	
}

Now if i want to get this session value in another method i got nil every time. don't know what goes wrong in my code.

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

答案1

得分: 2

你在GetSession函数中有一个错误。请将session变量更改为session1

另外,为了检查session值是否存在,最好按照以下方式进行:

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

You got a mistake at your GetSession function. Please change session variable to session1

Also to check if session value is present better do it this way:

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

答案2

得分: 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)
}

请注意,这只是一个代码示例,你可能需要根据自己的需求进行修改。

英文:

I don't know what value you what to get, but I assume you want a string value. I wrote simple func GetFoo() to get string value from session1.Values["foo"].

Full example below:

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

huangapple
  • 本文由 发表于 2015年4月8日 19:07:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/29512914.html
匿名

发表评论

匿名网友

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

确定