docs - ゴリラを見ると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)
}
その後、エンコードおよびクッキーの値をデコードするために必要な機能では、パッケージ全体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)
}
}
}
}
あなたはゴリラのセッションで使用される 'securecookie'ライブラリ内のコーデックの実装を見たことがありますか? https://github.com/gorilla/securecookie/blob/master/securecookie.go –
SecureCookieとは対照的に、Gorilla Sessionsを見るように指示してくれたので、私は当初は却下しました。しかし、そのパッケージを使用するのは理にかなっているので、共有してくれてありがとう! –