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"])
}
}
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
sì, l'ho controllato. ottenuto valore nil -> "non trovato" mentre si verifica la condizione per la sessione nel metodo GetSession(). –
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). –