Documentation
¶
Overview ¶
Package cookie provides encrypted HTTP cookie management with automatic expiration handling. It uses AES-256-GCM encryption to securely store cookie data with embedded timestamps for expiration validation.
Cookies must be initialized with New before use. Each cookie configuration maintains its own encryption key and is stored in memory for the lifetime of the application.
Example usage:
// Initialize a cookie with 1 hour expiration
err := cookie.New("session", 3600)
if err != nil {
log.Fatal(err)
}
// Save encrypted data and save cookie in http.Response
data := []byte("user123")
cookie.Save(w, "session", data)
// Retrieve and decrypt data from http.Request
data, err := cookie.Get(r, "session")
if err != nil {
// Handle expired or invalid cookie
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotInitialized is returned when attempting to operate on a cookie // that hasn't been initialized with New.returned when attempting to operate on a cookie. ErrNotInitialized = errors.New("not initialized") // ErrCookieExpired is returned when retrieving a cookie whose timestamp // exceeds its MaxAge. ErrCookieExpired = errors.New("expired cookie") // ErrExists is returned when attempting to create a cookie with a name // that already exists. ErrExists = errors.New("cookie exists") )
Functions ¶
func Clear ¶
func Clear(w http.ResponseWriter, name string, remove bool) error
Clear removes the cookie from the client by setting its MaxAge to -1. If remove is true, it also deletes the cookie configuration from memory. Returns ErrNotInitialized if the cookie hasn't been created with New.
func Get ¶
Get retrieves and decrypts the cookie data from the request. It verifies the cookie hasn't expired based on its embedded timestamp and MaxAge. Returns ErrNotInitialized if the cookie hasn't been created with New, ErrCookieExpired if the cookie has expired, or other errors for decryption failures.
func New ¶
New initializes a new encrypted cookie configuration with the given name and max age in seconds. It generates a random AES-256 key and nonce for encryption. Returns ErrExists if a cookie with the same name already exists.
func Save ¶
func Save(w http.ResponseWriter, name string, data []byte) error
Save add a timestamp, encrypts the provided data and timestampt, and sets it as an HTTP cookie in the response. The cookie is secured with HttpOnly, Secure, and SameSite flags. Returns ErrNotInitialized if the cookie hasn't been created with New.