go - 尝试从 gorilla SecureCookie读取时返回空 map

标签 go cookies gorilla

我编写了创建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/

相关文章:

Go:在我的 API 端点旁边提供静态页面(它们的端点)

go - 如何将 Go dep 与 GitLab 子组一起使用

google-app-engine - 使用 Google App Engine SDK 在 Go 中进行简单应用

go - 使用 go-client 在 Istio-resource 上设置 ObjectMeta

php - 如何让我的网站在用户关闭浏览器时自动注销?

json - 将 session 和 JSON 数据写入 http.ResponseWriter

amazon-web-services - 使用 API 代替 SDK 可以吗?

Asp.net共享表单由同一域中的两个应用程序进行身份验证

javascript - 检查 cookie 是否存在的更快更短的方法

unit-testing - 如何测试以确保函数被调用?