Looking at the docs - gorilla provides a secure cookie package.
Depending on your apps architecture - a basic implementation could work as follows:
Create a session management package to be used by your app. For the sake of example - lets call it sessionmngr
Inside of sessionmngr
, import "github.com/gorilla/securecookie"
.
In the sessionmngr
package, use a lower case init()
function to set up a private instance of securecookie
. Once a package is imported, lowercase init() functions are called in the order they are declared. (Check out the language spec for more info). You will use this instance to encode and decode cookies from the standard library's http.Request
.
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)
}
You will then use s
throughout the package in functions that need to encode and decode the a cookie's value. The securecookie package documentation provides a boilerplate example.
To meet the requirements of reading and modifying an already encrypted cookie - use the Decode
and Encode
methods on the instance of securecookie
that was setup in the example above.
Something Like ---
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)
}
}
}
}