我无法通过这种方式从会话中获得价值,它是nil:
session := initSession(r)
valWithOutType := session.Values[key]
Run Code Online (Sandbox Code Playgroud)
完整代码:
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
}
Run Code Online (Sandbox Code Playgroud)
输出:
myMac ~/forStack/session $ go run ./session.go
2015/01/30 16:47:26 Listening...
Run Code Online (Sandbox Code Playgroud)
首先,我打开网址http://localhost:3000/setSession并获取输出:
set session with key key and value value
Run Code Online (Sandbox Code Playgroud)
然后我打开url http://localhost:3000/getSession并获得输出:
valWithOutType: %!s(<nil>)
cannot get session value by key: key
value from session
Run Code Online (Sandbox Code Playgroud)
为什么valWithOutType是零,虽然我设定它要求/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
}
Run Code Online (Sandbox Code Playgroud)
在您的initSession()函数中,您可以更改商店选项:
store.Options = &sessions.Options{
MaxAge: 3600 * 1, // 1 hour
HttpOnly: true,
}
Run Code Online (Sandbox Code Playgroud)
该结构还包含cookie 将应用的Options重要字段。Path如果不设置它,它的默认值将为空字符串:""。这很可能会导致 cookie 不会与您的任何 url/路径匹配,因此无法找到您现有的会话。
添加一个路径来匹配您的所有网址,如下所示:
store.Options = &sessions.Options{
Path: "/", // to match all requests
MaxAge: 3600 * 1, // 1 hour
HttpOnly: true,
}
Run Code Online (Sandbox Code Playgroud)
此外,您不应该store.Options在每次调用中进行更改initSession(),因为您在每个传入请求中都调用了它。只需在创建时设置一次,store如下所示:
var store = sessions.NewCookieStore(authKey, encKey)
func init() {
store.Options = &sessions.Options{
Path: "/", // to match all requests
MaxAge: 3600 * 1, // 1 hour
HttpOnly: true,
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2046 次 |
| 最近记录: |