2015-01-30 12 views
5

non riesco a ottenere il valore dalla sessione in questo modo, è nil:non può ottenere il valore della sessione gorilla con il tasto

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

codice completo:

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 
} 

uscita:

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

First Apro l'url http://localhost:3000/setSession e ricevo l'output:

set session with key key and value value 

Poi ho Apri URL http://localhost:3000/getSession e ottenere in uscita:

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

Perché valWithOutType è pari a zero, anche se ho impostato la richiesta /setSession?

Aggiornamento

ho cambiato il codice in base alle @isza risposta, ma valore di sessione è ancora 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 
} 

risposta

1

Nella funzione initSession() si modificano le opzioni negozio:

store.Options = &sessions.Options{ 
    MaxAge: 3600 * 1, // 1 hour 
    HttpOnly: true, 
} 

Il Options struct contiene anche un importante Path campo a cui si applica il cookie. Se non lo si imposta, il suo valore predefinito sarà la stringa vuota: "". Questo probabilmente causerà che il cookie non verrà abbinato a nessuno dei tuoi URL/percorsi, quindi la tua sessione esistente non verrà trovata.

aggiungere un percorso per abbinare tutti gli URL come questo:

store.Options = &sessions.Options{ 
    Path:  "/",  // to match all requests 
    MaxAge: 3600 * 1, // 1 hour 
    HttpOnly: true, 
} 

Inoltre non dovrebbe cambiare store.Options in ogni chiamata di initSession() dal momento che si chiama questo in ogni richiesta in arrivo. Basta impostare questa volta quando si crea il tuo store in questo modo:

var store = sessions.NewCookieStore(authKey, encKey) 

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

scusate ma "Percorso" non ha aiutato. Si prega di consultare il mio aggiornamento sopra –

1

come non ho trovato risposta che ho deciso di non usare negozio di biscotto, ma usare Redis negozio per le sessioni. E ho trovato esempio funzionante completo 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")) 
} 
0

Cosa probabilmente stai facendo nella vostra funzione sessione di init con il metodo get si riavvia l'intera sessione di nuovo in modo che ogni volta che lo fai la sessione è vuota. Ho fatto un rapido trucco su ciò che hai scritto per mostrarti dove si trova il tuo errore. Si prega di aggirare questo esempio!

package appSession 

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

var appSession *sessions.Session; 

var authKey = []byte("qwer") 
var encKey = []byte("asdf") 

var store = sessions.NewCookieStore(authKey, encKey)  

func initSession(r *http.Request) *sessions.Session { 

    log.Println("session before get", appSession) 

    if appSession == nil {   
    }else{  
     return appSession;  
    } 

    session, err := store.Get(r, "golang_cookie") 
    appSession = session; 

    log.Println("session after get", session) 
    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) 
    log.Println("returned value: ", value); 

    if !ok { 
     fmt.Println("cannot get session value by key: " + key) 
    } 
    return value 
} 
Problemi correlati