Sessions

这个例子将会展示如何通过流行的 gorilla/sessions 会话 cookies.

cookie 是存储在用户浏览器中的小数据,并在每次请求时发送到服务器。在它们中,我们可以存储用户是否登录到我们的网站,并找出它时间上是谁(在我们系统中.

在本例中,我们只允许经过身份验证在/secret 页上查看隐私的信息。要访问它,首先要访问/login得到有效的会话cookie.此外,他可以访问/logout 来注销我们访问私密信息的权限.

  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!