Sessions

This example will show how to store data in session cookies using the popular gorilla/sessions package in Go.

Cookies are small pieces of data stored in the browser of a user and are sent to our server on each request. In them, we can store e.g. whether or not a user is logged in into our website and figure out who he actually is (in our system).

In this example we will only allow authenticated users to view our secret message on the /secret page. To get access to it, the will first have to visit /login to get a valid session cookie, which logs him in. Additionally he can visit /logout to revoke his access to our secret message.

  1. // sessions.go
  2. package main
  3. import (
  4. "fmt"
  5. "net/http"
  6. "github.com/gorilla/sessions"
  7. )
  8. var (
  9. // key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
  10. key = []byte("super-secret-key")
  11. store = sessions.NewCookieStore(key)
  12. )
  13. func secret(w http.ResponseWriter, r *http.Request) {
  14. session, _ := store.Get(r, "cookie-name")
  15. // Check if user is authenticated
  16. if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
  17. http.Error(w, "Forbidden", http.StatusForbidden)
  18. return
  19. }
  20. // Print secret message
  21. fmt.Fprintln(w, "The cake is a lie!")
  22. }
  23. func login(w http.ResponseWriter, r *http.Request) {
  24. session, _ := store.Get(r, "cookie-name")
  25. // Authentication goes here
  26. // ...
  27. // Set user as authenticated
  28. session.Values["authenticated"] = true
  29. session.Save(r, w)
  30. }
  31. func logout(w http.ResponseWriter, r *http.Request) {
  32. session, _ := store.Get(r, "cookie-name")
  33. // Revoke users authentication
  34. session.Values["authenticated"] = false
  35. session.Save(r, w)
  36. }
  37. func main() {
  38. http.HandleFunc("/secret", secret)
  39. http.HandleFunc("/login", login)
  40. http.HandleFunc("/logout", logout)
  41. http.ListenAndServe(":8080", nil)
  42. }
  1. $ go run sessions.go
  2. $ curl -s http://localhost:8080/secret
  3. Forbidden
  4. $ curl -s -I http://localhost:8080/login
  5. Set-Cookie: cookie-name=MTQ4NzE5Mz...
  6. $ curl -s --cookie "cookie-name=MTQ4NzE5Mz..." http://localhost:8080/secret
  7. The cake is a lie!