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

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

golang gorilla/session got nil value while checking session

问题

我已经导入了以下包:

  1. import (
  2. "github.com/gorilla/sessions"
  3. "github.com/gorilla/mux"
  4. //CORS
  5. "github.com/rs/cors"
  6. "github.com/justinas/alice"
  7. )

并定义了存储和主要方法如下:

  1. var store = sessions.NewCookieStore([]byte("something-very-secret"))
  2. const My_UI = "http://localhost:3000"
  3. func init() {
  4. store.Options = &sessions.Options{
  5. Path: "/",
  6. MaxAge: 3600 * 1, // 1 hour
  7. HttpOnly: true,
  8. }
  9. }
  10. var router = mux.NewRouter() //MUX Handeler
  11. //MAIN Function
  12. func main() {
  13. c := cors.New(cors.Options{
  14. AllowedOrigins: []string{My_UI},
  15. })
  16. router.HandleFunc("/submitted", Login)
  17. router.HandleFunc("/check", GetSession)
  18. http.Handle("/", router)
  19. chain := alice.New(c.Handler).Then(router) //CORS enable
  20. fmt.Println("server started at port 8080")
  21. http.ListenAndServe(":8080", chain)
  22. }

在我的方法中,我按照gorilla文档中的描述创建并设置了会话值:

  1. func Login(w http.ResponseWriter, r *http.Request) {
  2. fmt.Println("In login---------->")
  3. sess := GetCon() //get connection session
  4. defer sess.Close() //close session
  5. c := sess.DB("mydb").C("users") //collection-> select db table
  6. session1, _ := store.Get(r, "loginSession") //login session
  7. //parse json data
  8. form := LoginUser{}
  9. err := json.NewDecoder(r.Body).Decode(&form)
  10. if err !=nil {
  11. fmt.Println(err)
  12. }
  13. //get query data
  14. var result []Person
  15. errc1 := c.Find(bson.M{"email":form.Email,"password":form.Password}).All(&result)
  16. if errc1 != nil {
  17. js, err2 := json.Marshal("false")
  18. if err2 != nil{return}
  19. w.Header().Set("Content-Type", "application/json")
  20. w.Write(js)
  21. } else {
  22. if len(result)==0 {
  23. if err2 != nil {
  24. return
  25. }
  26. w.Header().Set("Content-Type", "application/json")
  27. w.Write(js)
  28. } else {
  29. fmt.Println("Success")
  30. session1.Values["foo"] = "bar"
  31. session1.Save(r, w)
  32. fmt.Println("saved",session1)
  33. js, err2 := json.Marshal(&result[0].Id)
  34. if err2 != nil {return}
  35. w.Header().Set("Content-Type", "application/json")
  36. w.Write(js)
  37. }
  38. }
  39. }

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

  1. func GetSession(w http.ResponseWriter, r *http.Request) {
  2. session1, _ := store.Get(r, "loginSession")
  3. fmt.Println("Session in SessionHandler", session1)
  4. if session.Values["foo"] == nil {
  5. fmt.Println("not found", session.Values["foo"])
  6. } else {
  7. fmt.Println("value", session.Values["foo"])
  8. }
  9. }
英文:

I have imported packages as

  1. import (
  2. "github.com/gorilla/sessions"
  3. "github.com/gorilla/mux"
  4. //CORS
  5. "github.com/rs/cors"
  6. "github.com/justinas/alice"
  7. )

and defined store and main method as follow

  1. var store = sessions.NewCookieStore([]byte("something-very-secret"))
  2. const My_UI="http://localhost:3000"
  3. func init() {
  4. store.Options = &sessions.Options{
  5. Path: "/",
  6. MaxAge: 3600 * 1, // 1 hour
  7. HttpOnly: true,
  8. }
  9. }
  10. var router = mux.NewRouter() //MUX Handeler
  11. //MAIN Function
  12. func main() {
  13. c := cors.New(cors.Options{
  14. AllowedOrigins: []string{My_UI},
  15. })
  16. router.HandleFunc("/submitted",Login)
  17. router.HandleFunc("/check",GetSession)
  18. http.Handle("/", router)
  19. chain := alice.New(c.Handler).Then(router) //CORS enable
  20. fmt.Println("server started at port 8080")
  21. http.ListenAndServe(":8080", chain)
  22. }

In my method I’ve created and set session value as describe in gorilla doc

  1. func Login(w http.ResponseWriter, r *http.Request) {
  2. fmt.Println("In login----------->")
  3. sess := GetCon() //get connection session
  4. defer sess.Close() //close session
  5. c := sess.DB("mydb").C("users") //collection-> select db table
  6. session1, _ := store.Get(r, "loginSession") //login session
  7. //parse json data
  8. form := LoginUser{}
  9. err := json.NewDecoder(r.Body).Decode(&form)
  10. if err !=nil {
  11. fmt.Println(err)
  12. }
  13. //get query data
  14. var result []Person
  15. errc1 := c.Find(bson.M{"email":form.Email,"password":form.Password}).All(&result)
  16. if errc1 != nil {
  17. js, err2 := json.Marshal("false")
  18. if err2 != nil{return}
  19. w.Header().Set("Content-Type", "application/json")
  20. w.Write(js)
  21. } else {
  22. if len(result)==0 {
  23. if err2 != nil {
  24. return
  25. }
  26. w.Header().Set("Content-Type", "application/json")
  27. w.Write(js)
  28. } else {
  29. fmt.Println("Success")
  30. session1.Values["foo"] = "bar"
  31. session1.Save(r, w)
  32. fmt.Println("saved",session1)
  33. js, err2 := json.Marshal(&result[0].Id)
  34. if err2 != nil {return}
  35. w.Header().Set("Content-Type", "application/json")
  36. w.Write(js)
  37. }
  38. }
  39. }

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.

  1. func GetSession(w http.ResponseWriter, r *http.Request) {
  2. session1, _ := store.Get(r, "loginSession")
  3. fmt.Println("Session in SessionHandler",session1)
  4. if session.Values["foo"] == nil {
  5. fmt.Println("not found",session.Values["foo"]))
  6. } else {
  7. fmt.Println("value",session.Values["foo"])
  8. }
  9. }

答案1

得分: 2

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

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

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

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:

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

答案2

得分: 1

我不知道你想要获取什么值,但我假设你想要一个字符串值。我编写了一个简单的 func GetFoo() 函数,用于从 session1.Values["foo"] 中获取字符串值。

完整的示例代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/gorilla/mux"
  6. "github.com/gorilla/sessions"
  7. "github.com/justinas/alice"
  8. "github.com/rs/cors"
  9. )
  10. var store = sessions.NewCookieStore([]byte("something-very-secret"))
  11. const My_UI = "http://localhost:3000"
  12. var router = mux.NewRouter() //MUX Handeler
  13. //MAIN Function
  14. func init() {
  15. store.Options = &sessions.Options{
  16. Path: "/",
  17. MaxAge: 3600 * 1, // 1 hour
  18. HttpOnly: true,
  19. }
  20. }
  21. func main() {
  22. c := cors.New(cors.Options{
  23. AllowedOrigins: []string{My_UI},
  24. })
  25. router.HandleFunc("/login", Login)
  26. router.HandleFunc("/check", GetSession)
  27. http.Handle("/", router)
  28. chain := alice.New(c.Handler).Then(router) //CORS enable
  29. fmt.Println("server started at port 8080")
  30. http.ListenAndServe(":8080", chain)
  31. }
  32. func GetFoo(f interface{}) string {
  33. if f != nil {
  34. if foo, ok := f.(string); ok {
  35. return foo
  36. }
  37. }
  38. return ""
  39. }
  40. func GetSession(w http.ResponseWriter, r *http.Request) {
  41. session1, _ := store.Get(r, "loginSession")
  42. foo := GetFoo(session1.Values["foo"])
  43. if foo == "" {
  44. fmt.Println("Foo is not set! Login to set value.")
  45. } else {
  46. fmt.Println("Foo Value:", foo, ".")
  47. }
  48. }
  49. func Login(w http.ResponseWriter, r *http.Request) {
  50. // Save Foo
  51. session1, _ := store.Get(r, "loginSession")
  52. session1.Values["foo"] = "bar"
  53. session1.Save(r, w)
  54. }

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

英文:

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:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/gorilla/mux"
  6. "github.com/gorilla/sessions"
  7. "github.com/justinas/alice"
  8. "github.com/rs/cors"
  9. )
  10. var store = sessions.NewCookieStore([]byte("something-very-secret"))
  11. const My_UI = "http://localhost:3000"
  12. var router = mux.NewRouter() //MUX Handeler
  13. //MAIN Function
  14. func init() {
  15. store.Options = &sessions.Options{
  16. Path: "/",
  17. MaxAge: 3600 * 1, // 1 hour
  18. HttpOnly: true,
  19. }
  20. }
  21. func main() {
  22. c := cors.New(cors.Options{
  23. AllowedOrigins: []string{My_UI},
  24. })
  25. router.HandleFunc("/login", Login)
  26. router.HandleFunc("/check", GetSession)
  27. http.Handle("/", router)
  28. chain := alice.New(c.Handler).Then(router) //CORS enable
  29. fmt.Println("server started at port 8080")
  30. http.ListenAndServe(":8080", chain)
  31. }
  32. func GetFoo(f interface{}) string {
  33. if f != nil {
  34. if foo, ok := f.(string); ok {
  35. return foo
  36. }
  37. }
  38. return ""
  39. }
  40. func GetSession(w http.ResponseWriter, r *http.Request) {
  41. session1, _ := store.Get(r, "loginSession")
  42. foo := GetFoo(session1.Values["foo"])
  43. if foo == "" {
  44. fmt.Println("Foo is not set! Login to set value.")
  45. } else {
  46. fmt.Println("Foo Value:", foo, ".")
  47. }
  48. }
  49. func Login(w http.ResponseWriter, r *http.Request) {
  50. // Save Foo
  51. session1, _ := store.Get(r, "loginSession")
  52. session1.Values["foo"] = "bar"
  53. session1.Save(r, w)
  54. }

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:

确定