【发布时间】:2020-08-29 00:48:03
【问题描述】:
我编写了创建 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
}
【问题讨论】:
-
map[sid:1686c951-e189-7205-52dc-e2cbb3a0e7ea username:AnnaZhao],这个map是编码前的cookie.Value,但是当我想从上面的函数中取回来时,它还给我空地图..
-
我也在文档中尝试了完全相同的代码,但也返回了空值..
-
网址是否使用https?
Secure属性设置为true,因此 cookie 只能在 https 上运行。 -
是的。 cookie 已成功编码并保存,我可以在 chrome 应用程序中看到。但是在解码cookie值时,它返回空...