无法通过键获取大猩猩会话值。

huangapple go评论90阅读模式
英文:

cannot get gorilla session value by key

问题

我无法以这种方式从会话中获取值,它是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 并获得输出:

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

为什么valWithOutTypenil,尽管我在请求/setSession时设置了它?

更新

我根据 @isza 的答案更改了代码,但会话值仍然是nil

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
}
英文:

I cannot get value from session this way, it is nil:

session := initSession(r)
valWithOutType := session.Values[key]

Full code:

package main
import (
&quot;fmt&quot;
&quot;github.com/gorilla/mux&quot;
&quot;github.com/gorilla/sessions&quot;
&quot;log&quot;
&quot;net/http&quot;
)
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc(&quot;/setSession&quot;, handler1).Methods(&quot;GET&quot;)
rtr.HandleFunc(&quot;/getSession&quot;, handler2).Methods(&quot;GET&quot;)
http.Handle(&quot;/&quot;, rtr)
log.Println(&quot;Listening...&quot;)
http.ListenAndServe(&quot;:3000&quot;, http.DefaultServeMux)
}
func handler1(w http.ResponseWriter, r *http.Request) {
SetSessionValue(w, r, &quot;key&quot;, &quot;value&quot;)
w.Write([]byte(&quot;setSession&quot;))
}
func handler2(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(&quot;getSession&quot;))
value := GetSessionValue(w, r, &quot;key&quot;)
fmt.Println(&quot;value from session&quot;)
fmt.Println(value)
}
var authKey = []byte(&quot;secret&quot;) // Authorization Key
var encKey = []byte(&quot;encKey&quot;) // Encryption Key
var store = sessions.NewCookieStore(authKey, encKey)
func initSession(r *http.Request) *sessions.Session {
store.Options = &amp;sessions.Options{
MaxAge:   3600 * 1, // 1 hour
HttpOnly: true,
}
session, err := store.Get(r, &quot;golang_cookie&quot;)
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(&quot;set session with key %s and value %s\n&quot;, 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(&quot;valWithOutType: %s\n&quot;, valWithOutType)
value, ok := valWithOutType.(string)
if !ok {
fmt.Println(&quot;cannot get session value by key: &quot; + key)
}
return value
}

Output:

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

First I open url http://localhost:3000/setSession and get output:

set session with key key and value value

Then I open url http://localhost:3000/getSession and get output:

valWithOutType: %!s(&lt;nil&gt;)
cannot get session value by key: key
value from session

Why valWithOutType is nil, although I set it requesting /setSession?

Update

I changed code according to @isza answer, but session value is still nil.

package main
import (
&quot;fmt&quot;
&quot;github.com/gorilla/mux&quot;
&quot;github.com/gorilla/sessions&quot;
&quot;log&quot;
&quot;net/http&quot;
)
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc(&quot;/setSession&quot;, handler1).Methods(&quot;GET&quot;)
rtr.HandleFunc(&quot;/getSession&quot;, handler2).Methods(&quot;GET&quot;)
http.Handle(&quot;/&quot;, rtr)
log.Println(&quot;Listening...&quot;)
store.Options = &amp;sessions.Options{
MaxAge:   3600 * 1, // 1 hour
HttpOnly: true,
Path:     &quot;/&quot;, // to match all requests
}
http.ListenAndServe(&quot;:3000&quot;, http.DefaultServeMux)
}
func handler1(w http.ResponseWriter, r *http.Request) {
SetSessionValue(w, r, &quot;key&quot;, &quot;value&quot;)
w.Write([]byte(&quot;setSession&quot;))
}
func handler2(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(&quot;getSession&quot;))
value := GetSessionValue(w, r, &quot;key&quot;)
fmt.Println(&quot;value from session&quot;)
fmt.Println(value)
}
var authKey = []byte(&quot;secret&quot;) // Authorization Key
var encKey = []byte(&quot;encKey&quot;) // Encryption Key
var store = sessions.NewCookieStore(authKey, encKey)
func initSession(r *http.Request) *sessions.Session {
session, err := store.Get(r, &quot;golang_cookie&quot;)
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(&quot;set session with key %s and value %s\n&quot;, 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(&quot;valWithOutType: %s\n&quot;, valWithOutType)
value, ok := valWithOutType.(string)
if !ok {
fmt.Println(&quot;cannot get session value by key: &quot; + key)
}
return value
}

答案1

得分: 3

你在initSession函数中使用get方法,可能是为了重新启动整个会话,所以每次执行时会清空会话。我对你的代码进行了一些快速修改,以显示出错误所在。请根据这个示例进行修改!

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 {
        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
}
英文:

What you are probably doing in your init session function with the get method you are restarting the whole session again so every time you do it the session is empty. I did a quick hack around what you wrote to show you where your error is. Please work around this example!

package appSession
import (        
&quot;net/http&quot;
&quot;fmt&quot;
&quot;log&quot;
&quot;github.com/gorilla/sessions&quot;    
)
var appSession *sessions.Session;
var authKey = []byte(&quot;qwer&quot;)
var encKey = []byte(&quot;asdf&quot;)
var store = sessions.NewCookieStore(authKey, encKey)    
func initSession(r *http.Request) *sessions.Session {
log.Println(&quot;session before get&quot;, appSession)
if appSession != nil {    
return appSession;    
}
session, err := store.Get(r, &quot;golang_cookie&quot;)
appSession = session;
log.Println(&quot;session after get&quot;, 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(&quot;set session with key %s and value %s\n&quot;, 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(&quot;valWithOutType: %s\n&quot;, valWithOutType)
value, ok := valWithOutType.(string)
log.Println(&quot;returned value: &quot;, value);
if !ok {
fmt.Println(&quot;cannot get session value by key: &quot; + key)
}
return value
}

答案2

得分: 1

在你的initSession()函数中,你改变了存储选项:

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

Options结构体还包含一个重要的Path字段,用于指定cookie适用的路径。如果你不设置它,它的默认值将为空字符串:""。这很可能导致cookie无法与任何URL/路径匹配,因此无法找到现有的会话。

添加一个路径以匹配所有的URL,像这样:

store.Options = &sessions.Options{
    Path:     "/",      // 匹配所有请求
    MaxAge:   3600 * 1, // 1小时
    HttpOnly: true,
}

此外,你不应该在每次调用initSession()时更改store.Options,因为你在每个传入的请求中调用它。只需在创建store时设置一次,像这样:

var store = sessions.NewCookieStore(authKey, encKey)

func init() {
    store.Options = &sessions.Options{
        Path:     "/",      // 匹配所有请求
        MaxAge:   3600 * 1, // 1小时
        HttpOnly: true,
    }
}
英文:

In your initSession() function you change the store options:

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

The Options struct also contains an important Path field to which the cookie will apply. If you don't set it, its default value will be the empty string: &quot;&quot;. This will most likely cause that the cookie will not be matched with any of your urls/paths, so your existing session will not be found.

Add a path to match all your urls like this:

store.Options = &amp;sessions.Options{
Path:     &quot;/&quot;,      // to match all requests
MaxAge:   3600 * 1, // 1 hour
HttpOnly: true,
}

Also you shouldn't change store.Options in each call of initSession() since you call this in each incoming request. Just set this once when you create your store like this:

var store = sessions.NewCookieStore(authKey, encKey)
func init() {
store.Options = &amp;sessions.Options{
Path:     &quot;/&quot;,      // to match all requests
MaxAge:   3600 * 1, // 1 hour
HttpOnly: true,
}
}

答案3

得分: 1

由于我没有找到答案,我决定不使用cookie存储,而是使用Redis存储会话。我在这里找到了一个完整的工作示例链接

package main

import (
    "fmt"
    "github.com/aaudis/GoRedisSession"
    "log"
    "net/http"
)

var (
    redis_session *rsess.SessionConnect
)

func main() {
    // 可配置参数
    rsess.Prefix = "sess:" // 会话前缀(在Redis中)
    rsess.Expire = 1800    // 30分钟会话过期

    // 连接到Redis并创建存储实例
    temp_sess, err := rsess.New("sid", 0, "127.0.0.1", 6379)
    if err != nil {
        log.Printf("%s", err)
    }

    redis_session = temp_sess // 分配给全局变量

    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会话存储示例:<br><br>
        <a href="/set">在会话中存储键</a><br>
        <a href="/get">从会话中获取键值</a><br>
        <a href="/des">销毁会话</a>
    `)
}

// 销毁会话
func Des(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    s.Destroy(w)
    fmt.Fprintf(w, "会话已删除!")
}

// 将变量设置到会话中
func Set(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    s.Set("UserID", "1000")
    fmt.Fprintf(w, "设置会话变量完成!")
}

// 从会话中获取变量
func Get(w http.ResponseWriter, r *http.Request) {
    s := redis_session.Session(w, r)
    fmt.Fprintf(w, "值 %s", s.Get("UserID"))
}

以上是一个使用Redis存储会话的完整工作示例。

英文:

As I have not found answer I decided not to use cookie store but use redis store for sessions. And I found full working example here

package main
import (
&quot;fmt&quot;
&quot;github.com/aaudis/GoRedisSession&quot;
&quot;log&quot;
&quot;net/http&quot;
)
var (
redis_session *rsess.SessionConnect
)
func main() {
// Configurable parameters
rsess.Prefix = &quot;sess:&quot; // session prefix (in Redis)
rsess.Expire = 1800    // 30 minute session expiration
// Connecting to Redis and creating storage instance
temp_sess, err := rsess.New(&quot;sid&quot;, 0, &quot;127.0.0.1&quot;, 6379)
if err != nil {
log.Printf(&quot;%s&quot;, err)
}
redis_session = temp_sess // assing to global variable
http.HandleFunc(&quot;/&quot;, Root)
http.HandleFunc(&quot;/get&quot;, Get)
http.HandleFunc(&quot;/set&quot;, Set)
http.HandleFunc(&quot;/des&quot;, Des)
http.ListenAndServe(&quot;:8888&quot;, nil)
}
func Root(w http.ResponseWriter, r *http.Request) {
w.Header().Add(&quot;Content-Type&quot;, &quot;text/html&quot;)
fmt.Fprintf(w, `
Redis session storage example:&lt;br&gt;&lt;br&gt;
&lt;a href=&quot;/set&quot;&gt;Store key in session&lt;/a&gt;&lt;br&gt;
&lt;a href=&quot;/get&quot;&gt;Get key value from session&lt;/a&gt;&lt;br&gt;
&lt;a href=&quot;/des&quot;&gt;Destroy session&lt;/a&gt;
`)
}
// Destroy session
func Des(w http.ResponseWriter, r *http.Request) {
s := redis_session.Session(w, r)
s.Destroy(w)
fmt.Fprintf(w, &quot;Session deleted!&quot;)
}
// Set variable to session
func Set(w http.ResponseWriter, r *http.Request) {
s := redis_session.Session(w, r)
s.Set(&quot;UserID&quot;, &quot;1000&quot;)
fmt.Fprintf(w, &quot;Setting session variable done!&quot;)
}
// Get variable from session
func Get(w http.ResponseWriter, r *http.Request) {
s := redis_session.Session(w, r)
fmt.Fprintf(w, &quot;Value %s&quot;, s.Get(&quot;UserID&quot;))
}

答案4

得分: 0

我玩了你的代码很长时间,最终发现它不起作用,因为你将加密密钥设置为非法值。

/gorilla/sessions文档中写道:

如果设置了加密密钥,它必须是16、24或32字节,以选择AES-128、AES-192或AES-256模式。

所以我认为var encKey = []byte("encKey")不符合这个要求。因此,首先根本没有设置cookie。

参考我的代码。我基本上添加了一些命令行输出,并使用了一个带有重定向的模板:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "html/template"
    "log"
    "net/http"
)

var authKey = []byte("secret") // 授权密钥

//var encKey = []byte("encKey") // 加密密钥

var store sessions.Store

func main() {
    rtr := mux.NewRouter()
    rtr.HandleFunc("/setSession/", handler1).Methods("GET")
    rtr.HandleFunc("/getSession/", handler2).Methods("GET")
    http.Handle("/", rtr)
    store = GetCookieStore()
    log.Println("Listening...")
    http.ListenAndServe(":4000", http.DefaultServeMux)

}

// 设置Cookie存储
func GetCookieStore() sessions.Store {

    //maxAge := 3600 * 1 // 1小时
    maxAge := 100
    //cookieStore := sessions.NewCookieStore(authKey, encKey)
    cookieStore := sessions.NewCookieStore(authKey)

    cookieStore.Options.HttpOnly = true
    cookieStore.Options.Path = "/" // 匹配所有请求
    cookieStore.MaxAge(maxAge)

    return cookieStore
}

func handler1(w http.ResponseWriter, r *http.Request) {
    t, _ := template.New("foo").Parse(getSessionTemplate)

    SetSessionValue(w, r, "key", "value")
    session := initSession(r)
    fmt.Print("handler1: ")
    fmt.Println(session)

    Value, ok := session.Values["key"].(string)
    if !ok {
        fmt.Println("类型断言为字符串失败或无法检索到会话值。")
    }

    t.Execute(w, Value)

}

func handler2(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("getSession"))
    session := initSession(r)
    fmt.Print("handler2: ")
    fmt.Println(session)
    value := GetSessionValue(w, r, "key")
    fmt.Println("来自会话的值")
    fmt.Println(value)
}

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("设置带有键%s和值%s的会话\n", key, value)
    session.Save(r, w)
    fmt.Print("setsession: ")
    fmt.Println(session)
}

func GetSessionValue(w http.ResponseWriter, r *http.Request, key string) string {
    session := initSession(r)
    fmt.Print("getsession: ")
    fmt.Println(session)
    valWithOutType := session.Values[key]
    fmt.Printf("valWithOutType: %s\n", valWithOutType)
    value, ok := valWithOutType.(string)
    if !ok {
        fmt.Println("无法通过键获取会话值:" + key)
    }

    return value
}

var getSessionTemplate = `
<p><label>设置的会话值:</label></p>
<p><label>值:现在是:{{.}}</label></p>

<p><a href="/getSession/">获取会话</a></p>`
英文:

I played with your code for a long time and finally found out that it does not work, because you set the encryption key to an illegal value.

In the /gorilla/sessions documentation it says:

> The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.

So since I believe that var encKey = []byte(&quot;encKey&quot;) simply does not follow this requirement. In turn, the cookie is not set in the first place.

See my code for reference. I basically added some more command line output and used a template with a redirect:

package main
import (
&quot;fmt&quot;
&quot;github.com/gorilla/mux&quot;
&quot;github.com/gorilla/sessions&quot;
&quot;html/template&quot;
&quot;log&quot;
&quot;net/http&quot;
)
var authKey = []byte(&quot;secret&quot;) // Authorization Key
//var encKey = []byte(&quot;encKey&quot;) // Encryption Key
var store sessions.Store
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc(&quot;/setSession/&quot;, handler1).Methods(&quot;GET&quot;)
rtr.HandleFunc(&quot;/getSession/&quot;, handler2).Methods(&quot;GET&quot;)
http.Handle(&quot;/&quot;, rtr)
store = GetCookieStore()
log.Println(&quot;Listening...&quot;)
http.ListenAndServe(&quot;:4000&quot;, http.DefaultServeMux)
}
//setting up the cookiestore
func GetCookieStore() sessions.Store {
//maxAge := 3600 * 1 // 1 hour
maxAge := 100
//cookieStore := sessions.NewCookieStore(authKey, encKey)
cookieStore := sessions.NewCookieStore(authKey)
cookieStore.Options.HttpOnly = true
cookieStore.Options.Path = &quot;/&quot; // to match all requests
cookieStore.MaxAge(maxAge)
return cookieStore
}
func handler1(w http.ResponseWriter, r *http.Request) {
t, _ := template.New(&quot;foo&quot;).Parse(getSessionTemplate)
SetSessionValue(w, r, &quot;key&quot;, &quot;value&quot;)
session := initSession(r)
fmt.Print(&quot;handler1: &quot;)
fmt.Println(session)
Value, ok := session.Values[&quot;key&quot;].(string)
if !ok {
fmt.Println(&quot;Type assertion to string failed or session value could not be retrieved.&quot;)
}
t.Execute(w, Value)
}
func handler2(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(&quot;getSession&quot;))
session := initSession(r)
fmt.Print(&quot;handler2: &quot;)
fmt.Println(session)
value := GetSessionValue(w, r, &quot;key&quot;)
fmt.Println(&quot;value from session&quot;)
fmt.Println(value)
}
func initSession(r *http.Request) *sessions.Session {
session, err := store.Get(r, &quot;_golang_cookie&quot;)
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(&quot;set session with key %s and value %s\n&quot;, key, value)
session.Save(r, w)
fmt.Print(&quot;setsession: &quot;)
fmt.Println(session)
}
func GetSessionValue(w http.ResponseWriter, r *http.Request, key string) string {
session := initSession(r)
fmt.Print(&quot;getsession: &quot;)
fmt.Println(session)
valWithOutType := session.Values[key]
fmt.Printf(&quot;valWithOutType: %s\n&quot;, valWithOutType)
value, ok := valWithOutType.(string)
if !ok {
fmt.Println(&quot;cannot get session value by key: &quot; + key)
}
return value
}
var getSessionTemplate = `
&lt;p&gt;&lt;label&gt;Session value set:&lt;/label&gt;&lt;/p&gt;
&lt;p&gt;&lt;label&gt;Value: is now: {{.}}&lt;/label&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;/getSession/&quot;&gt;Getsession&lt;/a&gt;&lt;/p&gt;`

huangapple
  • 本文由 发表于 2015年1月30日 22:17:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/28237806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定