Documentation ¶
Overview ¶
Package sessions provides secure client-side storage of session data.
Index ¶
Examples ¶
Constants ¶
View Source
const KeySize = 32 // 256-bit keys
Variables ¶
View Source
var ErrMissing = errors.New("value is missing")
Functions ¶
This section is empty.
Types ¶
type Store ¶
type Store struct { // Ciphers provide authenticated encryption for stored data. When creating // new encrypted blobs, the first cipher is used. When decrypting existing // blobs, to allow for key rotation, all ciphers are attempted. Ciphers []cipher.AEAD // CookieTemplate is required if using the Store's cookie methods. // SetCookie won't modify the Expires field, so use MaxAge instead. CookieTemplate http.Cookie }
A Store provides a mechanism for securely storing small pieces of session data on a client.
Example (Cookie) ¶
package main import ( "fmt" "log" "net/http" "time" "github.com/jonstaryuk/sessions" ) var key [sessions.KeySize]byte func main() { // Define a type to hold the session data you want to save on the client. // Only include the most essential data, since HTTP cookies have limited // storage capacity (around 4 KB). type Session struct { UserID int SessionID string Started time.Time } // Create a Store when you initialize your server. store, err := sessions.NewStore(key) if err != nil { panic(err) } store.CookieTemplate = http.Cookie{ Name: "myapp_session", Path: "/", MaxAge: 7 * 24 * 60 * 60, } // Save the data to the client when a user successfully logs in. http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { // ... authenticate the user ... sess := Session{ UserID: 12345, SessionID: "example", Started: time.Now(), } if err := store.SetCookie(w, sess); err != nil { log.Println(err) http.Error(w, "internal error", http.StatusInternalServerError) return } fmt.Fprintln(w, "OK") }) // Retrieve the data as desired. http.HandleFunc("/my_account", func(w http.ResponseWriter, r *http.Request) { var sess Session if err := store.GetFromCookie(r, &sess); err != nil { if err != sessions.ErrMissing { log.Println(err) } http.Error(w, "not logged in", http.StatusForbidden) return } fmt.Fprintf(w, "Logged in as user %d", sess.UserID) }) }
Output:
func (*Store) GetFromCookie ¶
GetFromCookie retrieves data saved using s.SetCookie. It returns ErrMissing if the cookie is missing, and may return other kinds of errors as applicable.
Click to show internal directories.
Click to hide internal directories.