当试图从gorilla SecureCookie中读取时,返回空地图。

问题描述 投票:0回答:1

我按照GoDoc和gorilla api中的文档,写了一些函数来创建一个SecureCookie并读取这个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
}
go cookies gorilla
1个回答
0
投票

由于区块作用域的原因,读取函数中的错误可能会被默默忽略。

相反,要尽快检查并返回错误。例如,在读取函数中,返回的错误可能会解释问题。

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?

© www.soinside.com 2019 - 2024. All rights reserved.