不能通过密钥获得大猩猩会话值 [英] cannot get gorilla session value by key

查看:128
本文介绍了不能通过密钥获得大猩猩会话值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过这种方式从会话中获得价值,它是 nil

I cannot get value from session this way, it is nil:

session := initSession(r)
valWithOutType := session.Values[key]

完整代码:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "log"
    "net/http"
)

func main() {
    rtr := mux.NewRouter()
    rtr.HandleFunc("/setSession", handler1).Methods("GET")
    rtr.HandleFunc("/getSession", handler2).Methods("GET")
    http.Handle("/", rtr)
    log.Println("Listening...")
    http.ListenAndServe(":3000", http.DefaultServeMux)
}

func handler1(w http.ResponseWriter, r *http.Request) {
    SetSessionValue(w, r, "key", "value")
    w.Write([]byte("setSession"))
}

func handler2(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("getSession"))
    value := GetSessionValue(w, r, "key")
    fmt.Println("value from session")
    fmt.Println(value)
}

var authKey = []byte("secret") // Authorization Key

var encKey = []byte("encKey") // Encryption Key

var store = sessions.NewCookieStore(authKey, encKey)

func initSession(r *http.Request) *sessions.Session {
    store.Options = &sessions.Options{
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
    }
    session, err := store.Get(r, "golang_cookie")
    if err != nil {
        panic(err)
    }

    return session
}

func SetSessionValue(w http.ResponseWriter, r *http.Request, key, value string) {
    session := initSession(r)
    session.Values[key] = value
    fmt.Printf("set session with key %s and value %s\n", key, value)
    session.Save(r, w)
}

func GetSessionValue(w http.ResponseWriter, r *http.Request, key string) string {
    session := initSession(r)
    valWithOutType := session.Values[key]
    fmt.Printf("valWithOutType: %s\n", valWithOutType)
    value, ok := valWithOutType.(string)
    if !ok {
        fmt.Println("cannot get session value by key: " + key)
    }
    return value
}

输出:

Output:

myMac ~/forStack/session $ go run ./session.go
2015/01/30 16:47:26 Listening...

首先我打开url http:// localhost:3000 / setSession 并获取输出:

First I open url http://localhost:3000/setSession and get output:

set session with key key and value value

b

valWithOutType: %!s(<nil>)
cannot get session value by key: key
value from session

为什么 valWithOutType 是零,但我设定了它请求 / setSession

Why valWithOutType is nil, although I set it requesting /setSession?

代码根据@isza答案,但会话值仍然是 nil

I changed code according to @isza answer, but session value is still nil.

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "log"
    "net/http"
)

func main() {
    rtr := mux.NewRouter()
    rtr.HandleFunc("/setSession", handler1).Methods("GET")
    rtr.HandleFunc("/getSession", handler2).Methods("GET")
    http.Handle("/", rtr)
    log.Println("Listening...")
    store.Options = &sessions.Options{
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
        Path:     "/", // to match all requests
    }
    http.ListenAndServe(":3000", http.DefaultServeMux)

}

func handler1(w http.ResponseWriter, r *http.Request) {
    SetSessionValue(w, r, "key", "value")
    w.Write([]byte("setSession"))
}

func handler2(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("getSession"))
    value := GetSessionValue(w, r, "key")
    fmt.Println("value from session")
    fmt.Println(value)
}

var authKey = []byte("secret") // Authorization Key

var encKey = []byte("encKey") // Encryption Key

var store = sessions.NewCookieStore(authKey, encKey)

func initSession(r *http.Request) *sessions.Session {
    session, err := store.Get(r, "golang_cookie")
    if err != nil {
        panic(err)
    }
    return session
}

func SetSessionValue(w http.ResponseWriter, r *http.Request, key, value string) {
    session := initSession(r)
    session.Values[key] = value
    fmt.Printf("set session with key %s and value %s\n", key, value)
    session.Save(r, w)
}

func GetSessionValue(w http.ResponseWriter, r *http.Request, key string) string {
    session := initSession(r)
    valWithOutType := session.Values[key]
    fmt.Printf("valWithOutType: %s\n", valWithOutType)
    value, ok := valWithOutType.(string)
    if !ok {
        fmt.Println("cannot get session value by key: " + key)
    }
    return value
}


推荐答案

没有找到答案我决定不使用cookie存储,而是使用redis存储进行会话。我找到了完整的工作示例此处

As I have not found answer I decided not to use cookie store but use redis store for sessions. And I found full working example here

package main

import (
    "fmt"
    "github.com/aaudis/GoRedisSession"
    "log"
    "net/http"
)

var (
    redis_session *rsess.SessionConnect
)

func main() {
    // Configurable parameters
    rsess.Prefix = "sess:" // session prefix (in Redis)
    rsess.Expire = 1800    // 30 minute session expiration

    // Connecting to Redis and creating storage instance
    temp_sess, err := rsess.New("sid", 0, "127.0.0.1", 6379)
    if err != nil {
        log.Printf("%s", err)
    }

    redis_session = temp_sess // assing to global variable

    http.HandleFunc("/", Root)
    http.HandleFunc("/get", Get)
    http.HandleFunc("/set", Set)
    http.HandleFunc("/des", Des)
    http.ListenAndServe(":8888", nil)
}

func Root(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "text/html")
    fmt.Fprintf(w, `
        Redis session storage example:<br><br>
        <a href="/set">Store key in session</a><br>
        <a href="/get">Get key value from session</a><br>
        <a href="/des">Destroy session</a>
    `)
}

// Destroy session
func Des(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    s.Destroy(w)
    fmt.Fprintf(w, "Session deleted!")
}

// Set variable to session
func Set(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    s.Set("UserID", "1000")
    fmt.Fprintf(w, "Setting session variable done!")
}

// Get variable from session
func Get(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    fmt.Fprintf(w, "Value %s", s.Get("UserID"))
}

这篇关于不能通过密钥获得大猩猩会话值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆