我编写了创建SecureCookie的函数,并按照GoDoc和gorilla api中的文档阅读了此SecureCookie。 SecureCookie已成功创建并打印出来,但是当我尝试从此编码的cookie中读取值时,它返回了一个空映射。有人可以帮我弄清楚代码出什么问题吗?
var hashKey []byte
var blockKey []byte
var s *securecookie.SecureCookie
func init() {
hashKey = []byte{61, 55, 215, 133, 151, 242, 106, 54, 241, 162, 37, 3, 98, 73, 102, 33, 164, 246, 127, 157, 31, 190, 240, 40, 30, 104, 15, 161, 180, 214, 162, 107}
blockKey = []byte{78, 193, 30, 249, 192, 210, 229, 31, 223, 133, 209, 112, 58, 226, 16, 172, 63, 86, 12, 107, 7, 76, 111, 48, 131, 65, 153, 126, 138, 250, 200, 46}
s = securecookie.New(hashKey, blockKey)
}
func CreateSecureCookie(u *models.User, sessionID string, w http.ResponseWriter, r *http.Request) error {
value := map[string]string{
"username": u.Username,
"sid": sessionID,
}
if encoded, err := s.Encode("session", value); err == nil {
cookie := &http.Cookie{
Name: "session",
Value: encoded,
Path: "/",
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, cookie)
} else {
log.Println("Error happened when encode secure cookie:", err)
return err
}
return nil
}
func ReadSecureCookieValues(w http.ResponseWriter, r *http.Request) (map[string]string, error) {
if cookie, err := r.Cookie("session"); err == nil {
value := make(map[string]string)
if err = s.Decode("session", cookie.Value, &value); err == nil {
return value, nil
}
return nil, err
}
return nil, nil
}
最佳答案
由于块作用域的原因,在读取功能中可能会默默忽略错误。
相反,请尽快检查并返回错误。例如:
func ReadSecureCookieValues(w http.ResponseWriter, r *http.Request) (map[string]string, error) {
cookie, err := r.Cookie("session")
if err != nil {
return nil, err
}
value := make(map[string]string)
err = s.Decode("session", cookie.Value, &value)
if err != nil {
return nil, err
}
return value, nil
}
返回的错误可能解释了问题。也许找不到cookie?
关于go - 尝试从 gorilla SecureCookie读取时返回空 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61764250/