2015-04-08 10 views
5

Ho importato pacchetti comegolang gorilla/sessione ha valore nullo durante il controllo di sessione

import (
    "github.com/gorilla/sessions" 
    "github.com/gorilla/mux" 

    //CORS 
    "github.com/rs/cors" 
    "github.com/justinas/alice" 
) 

e negozio e principale metodo definito come seguire

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

Nel mio metodo che ho creato e impostato la sessione valore come descritto 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) 
     }  
    } 
} 

Ora se voglio ottenere questo valore di sessione in un altro metodo ho zero ogni volta. non so cosa vada storto nel mio codice.

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

Hai controllato per errori? Sembra che tu li stia ignorando nel codice di esempio. Se dovessi indovinare, direi che hai già scritto su 'http.ResponseWriter' prima di salvare la sessione (intestazioni inviate). – seong

+0

sì, l'ho controllato. ottenuto valore nil -> "non trovato " mentre si verifica la condizione per la sessione nel metodo GetSession(). –

+0

in base al doc (gorilla) per salvare qualsiasi sessione, dobbiamo scrivere session.Save (r, w) .. e per più sessioni hanno menzionato session.Save (r, w). –

risposta

1

Non so quale valore si ottenga, ma presumo che si desideri un valore stringa. Ho scritto semplice func GetFoo() per ottenere il valore stringa da session1.Values["foo"].

completa esempio qui sotto:

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

Hai un errore alla vostra funzione getSession. Per favore cambia session variabile session1

anche per verificare se il valore della sessione è presente meglio fare in questo modo:

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