Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang gorilla/session got nil value while checking session

Tags:

go

gorilla

I have imported packages as

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

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

and defined store and main method as follow

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

In my method I’ve created and set session value as describe 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) 
        }       
    }   
}

Now if i want to get this session value in another method i got nil every time. don't know what goes wrong in my code.

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"])
    }
}
like image 216
Mrugank Dhimmar Avatar asked Oct 20 '22 14:10

Mrugank Dhimmar


2 Answers

You got a mistake at your GetSession function. Please change session variable to session1

Also to check if session value is present better do it this way:

session, err := store.Get(r, ssid)
    if err == nil {
        if value, ok := session.Values["foo"].(string); ok {
            session_data = value
        }
    }
like image 105
Marsel Novy Avatar answered Dec 06 '22 05:12

Marsel Novy


I don't know what value you what to get, but I assume you want a string value. I wrote simple func GetFoo() to get string value from session1.Values["foo"].

Full example below:

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)
}
like image 25
Kroksys Avatar answered Dec 06 '22 05:12

Kroksys