本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
7.0KB

  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. /*
  5. Package sessions provides cookie and filesystem sessions and
  6. infrastructure for custom session backends.
  7. The key features are:
  8. * Simple API: use it as an easy way to set signed (and optionally
  9. encrypted) cookies.
  10. * Built-in backends to store sessions in cookies or the filesystem.
  11. * Flash messages: session values that last until read.
  12. * Convenient way to switch session persistency (aka "remember me") and set
  13. other attributes.
  14. * Mechanism to rotate authentication and encryption keys.
  15. * Multiple sessions per request, even using different backends.
  16. * Interfaces and infrastructure for custom session backends: sessions from
  17. different stores can be retrieved and batch-saved using a common API.
  18. Let's start with an example that shows the sessions API in a nutshell:
  19. import (
  20. "net/http"
  21. "github.com/gorilla/sessions"
  22. )
  23. // Note: Don't store your key in your source code. Pass it via an
  24. // environmental variable, or flag (or both), and don't accidentally commit it
  25. // alongside your code. Ensure your key is sufficiently random - i.e. use Go's
  26. // crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
  27. var store = sessions.NewCookieStore(os.Getenv("SESSION_KEY"))
  28. func MyHandler(w http.ResponseWriter, r *http.Request) {
  29. // Get a session. Get() always returns a session, even if empty.
  30. session, err := store.Get(r, "session-name")
  31. if err != nil {
  32. http.Error(w, err.Error(), http.StatusInternalServerError)
  33. return
  34. }
  35. // Set some session values.
  36. session.Values["foo"] = "bar"
  37. session.Values[42] = 43
  38. // Save it before we write to the response/return from the handler.
  39. session.Save(r, w)
  40. }
  41. First we initialize a session store calling NewCookieStore() and passing a
  42. secret key used to authenticate the session. Inside the handler, we call
  43. store.Get() to retrieve an existing session or a new one. Then we set some
  44. session values in session.Values, which is a map[interface{}]interface{}.
  45. And finally we call session.Save() to save the session in the response.
  46. Note that in production code, we should check for errors when calling
  47. session.Save(r, w), and either display an error message or otherwise handle it.
  48. Save must be called before writing to the response, otherwise the session
  49. cookie will not be sent to the client.
  50. That's all you need to know for the basic usage. Let's take a look at other
  51. options, starting with flash messages.
  52. Flash messages are session values that last until read. The term appeared with
  53. Ruby On Rails a few years back. When we request a flash message, it is removed
  54. from the session. To add a flash, call session.AddFlash(), and to get all
  55. flashes, call session.Flashes(). Here is an example:
  56. func MyHandler(w http.ResponseWriter, r *http.Request) {
  57. // Get a session.
  58. session, err := store.Get(r, "session-name")
  59. if err != nil {
  60. http.Error(w, err.Error(), http.StatusInternalServerError)
  61. return
  62. }
  63. // Get the previous flashes, if any.
  64. if flashes := session.Flashes(); len(flashes) > 0 {
  65. // Use the flash values.
  66. } else {
  67. // Set a new flash.
  68. session.AddFlash("Hello, flash messages world!")
  69. }
  70. session.Save(r, w)
  71. }
  72. Flash messages are useful to set information to be read after a redirection,
  73. like after form submissions.
  74. There may also be cases where you want to store a complex datatype within a
  75. session, such as a struct. Sessions are serialised using the encoding/gob package,
  76. so it is easy to register new datatypes for storage in sessions:
  77. import(
  78. "encoding/gob"
  79. "github.com/gorilla/sessions"
  80. )
  81. type Person struct {
  82. FirstName string
  83. LastName string
  84. Email string
  85. Age int
  86. }
  87. type M map[string]interface{}
  88. func init() {
  89. gob.Register(&Person{})
  90. gob.Register(&M{})
  91. }
  92. As it's not possible to pass a raw type as a parameter to a function, gob.Register()
  93. relies on us passing it a value of the desired type. In the example above we've passed
  94. it a pointer to a struct and a pointer to a custom type representing a
  95. map[string]interface. (We could have passed non-pointer values if we wished.) This will
  96. then allow us to serialise/deserialise values of those types to and from our sessions.
  97. Note that because session values are stored in a map[string]interface{}, there's
  98. a need to type-assert data when retrieving it. We'll use the Person struct we registered above:
  99. func MyHandler(w http.ResponseWriter, r *http.Request) {
  100. session, err := store.Get(r, "session-name")
  101. if err != nil {
  102. http.Error(w, err.Error(), http.StatusInternalServerError)
  103. return
  104. }
  105. // Retrieve our struct and type-assert it
  106. val := session.Values["person"]
  107. var person = &Person{}
  108. if person, ok := val.(*Person); !ok {
  109. // Handle the case that it's not an expected type
  110. }
  111. // Now we can use our person object
  112. }
  113. By default, session cookies last for a month. This is probably too long for
  114. some cases, but it is easy to change this and other attributes during
  115. runtime. Sessions can be configured individually or the store can be
  116. configured and then all sessions saved using it will use that configuration.
  117. We access session.Options or store.Options to set a new configuration. The
  118. fields are basically a subset of http.Cookie fields. Let's change the
  119. maximum age of a session to one week:
  120. session.Options = &sessions.Options{
  121. Path: "/",
  122. MaxAge: 86400 * 7,
  123. HttpOnly: true,
  124. }
  125. Sometimes we may want to change authentication and/or encryption keys without
  126. breaking existing sessions. The CookieStore supports key rotation, and to use
  127. it you just need to set multiple authentication and encryption keys, in pairs,
  128. to be tested in order:
  129. var store = sessions.NewCookieStore(
  130. []byte("new-authentication-key"),
  131. []byte("new-encryption-key"),
  132. []byte("old-authentication-key"),
  133. []byte("old-encryption-key"),
  134. )
  135. New sessions will be saved using the first pair. Old sessions can still be
  136. read because the first pair will fail, and the second will be tested. This
  137. makes it easy to "rotate" secret keys and still be able to validate existing
  138. sessions. Note: for all pairs the encryption key is optional; set it to nil
  139. or omit it and and encryption won't be used.
  140. Multiple sessions can be used in the same request, even with different
  141. session backends. When this happens, calling Save() on each session
  142. individually would be cumbersome, so we have a way to save all sessions
  143. at once: it's sessions.Save(). Here's an example:
  144. var store = sessions.NewCookieStore([]byte("something-very-secret"))
  145. func MyHandler(w http.ResponseWriter, r *http.Request) {
  146. // Get a session and set a value.
  147. session1, _ := store.Get(r, "session-one")
  148. session1.Values["foo"] = "bar"
  149. // Get another session and set another value.
  150. session2, _ := store.Get(r, "session-two")
  151. session2.Values[42] = 43
  152. // Save all sessions.
  153. sessions.Save(r, w)
  154. }
  155. This is possible because when we call Get() from a session store, it adds the
  156. session to a common registry. Save() uses it to save all registered sessions.
  157. */
  158. package sessions
上海开阖软件有限公司 沪ICP备12045867号-1