drxrgundk062317205 2015-04-08 11:07
浏览 50

在检查会话时,golang大猩猩/会话的值为零

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"])
    }
}
  • 写回答

2条回答 默认 最新

  • doutan1857 2016-10-24 08:32
    关注

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

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算