2015-01-30 2 views
5

에 의해 고릴라 세션 값을 얻을 수 없다, 그것은 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 
} 

출력 :

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

우선 나는 URL http://localhost:3000/setSession을 열고 산출을 얻는다 :

set session with key key and value value 

은 그 때 나는 URL http://localhost:3000/getSession을 열고 얻을 출력 : 나는 /setSession를 요청하는 설정하지만 valWithOutType이 전무가, 왜

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

?

업데이트 나는 @isza 대답에 따라 코드를 변경하지만, 세션 값은 여전히 ​​nil입니다. 당신의 initSession() 기능에

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 
} 

답변

1

당신은 상점 옵션을 변경 :

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

Options 구조체는 쿠키가 적용되는 중요한 Path 필드가 포함되어 있습니다. 설정하지 않으면 기본값은 빈 문자열 ""이됩니다. 이렇게하면 쿠키가 URL/경로와 일치하지 않아 기존 세션을 찾을 수 없게됩니다.

는 경로가 이런 모든 URL에 맞게 추가 : 각 들어오는 요청이 전화 때문에
store.Options = &sessions.Options{ 
    Path:  "/",  // to match all requests 
    MaxAge: 3600 * 1, // 1 hour 
    HttpOnly: true, 
} 

은 또한 당신이 initSession()의 각 호출에 store.Options을 변경하지 마십시오. 그냥 당신이이처럼 store를 만들 때 한번 설정 :

내가 쿠키 저장소를 사용하지만 세션 레디 스 저장소를 사용하지 않기로 결정 답을 찾을 수없는 것처럼
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

미안하지만 '경로'는 도움이되지 않았습니다. 위의 내 업데이트를 참조하십시오. –

1

. 그리고 당신이 그것을 세션이 비어 할 당신은 아마 당신이 다시 그렇게 할 때마다 전체 세션을 다시 시작하는 get 메소드와 초기화 세션 기능에 뭐하는 전체 작업 예를 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

을 발견했다. 나는 당신이 당신의 실수가 어디에 있는지를 보여주기 위해 당신이 작성한 것을 빠르게 해킹했다. 이 예제를 해결하십시오!

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 
} 
관련 문제