查看文档 - gorilla 提供了 secure cookie package。
根据您的应用架构 - 基本实现可以按如下方式工作:
创建一个供您的应用使用的会话管理包。举个例子 - 让我们称之为sessionmngr
在sessionmngr 内部,导入"github.com/gorilla/securecookie"。
在sessionmngr 包中,使用小写的init() 函数来设置securecookie 的私有实例。导入包后,将按照声明的顺序调用小写的 init() 函数。 (查看语言spec 了解更多信息)。您将使用此实例对来自标准库的http.Request 的 cookie 进行编码和解码。
import (
"github.com/gorilla/securecookie"
//you will need this later
"http"
)
//declare private secure cookie
var s *securecookie.SecureCookie
//initialize it here (taken from the gorilla docs example)
func init() {
var hashKey = []byte("very-secret")
var blockKey = []byte("a-lot-secret")
s = securecookie.New(hashKey, blockKey)
}
然后,您将在需要对 cookie 的值进行编码和解码的函数中的整个包中使用 s。 securecookie package documentation 提供了一个样板示例。
为了满足读取和修改已加密 cookie 的要求 - 在上面示例中设置的 securecookie 实例上使用 Decode 和 Encode 方法。
有点像 ---
func DecodeAndModify(w http.ResponseWriter, r *http.Request) {
//get reference to cookie if set
if cookie, err := r.Cookie("cookie-name"); err == nil {
value := make(map[string]string)
//use Decode to get the value from the cookie
if err = s.Decode("cookie-name", cookie.Value, &value); err == nil {
//modify the value in some way
value["newKey"] = "newValue"
//re-encode it
if encoded, err := s.Encode("cookie-name", value); err == nil {
cookie := &http.Cookie{
Name: "cookie-name",
Value: encoded,
Path: "/",
}
http.SetCookie(w, cookie)
}
}
}
}