doc.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 gorilla/context stores values shared during a request lifetime.
  6. For example, a router can set variables extracted from the URL and later
  7. application handlers can access those values, or it can be used to store
  8. sessions values to be saved at the end of a request. There are several
  9. others common uses.
  10. The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
  11. http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
  12. Here's the basic usage: first define the keys that you will need. The key
  13. type is interface{} so a key can be of any type that supports equality.
  14. Here we define a key using a custom int type to avoid name collisions:
  15. package foo
  16. import (
  17. "github.com/gorilla/context"
  18. )
  19. type key int
  20. const MyKey key = 0
  21. Then set a variable. Variables are bound to an http.Request object, so you
  22. need a request instance to set a value:
  23. context.Set(r, MyKey, "bar")
  24. The application can later access the variable using the same key you provided:
  25. func MyHandler(w http.ResponseWriter, r *http.Request) {
  26. // val is "bar".
  27. val := context.Get(r, foo.MyKey)
  28. // returns ("bar", true)
  29. val, ok := context.GetOk(r, foo.MyKey)
  30. // ...
  31. }
  32. And that's all about the basic usage. We discuss some other ideas below.
  33. Any type can be stored in the context. To enforce a given type, make the key
  34. private and wrap Get() and Set() to accept and return values of a specific
  35. type:
  36. type key int
  37. const mykey key = 0
  38. // GetMyKey returns a value for this package from the request values.
  39. func GetMyKey(r *http.Request) SomeType {
  40. if rv := context.Get(r, mykey); rv != nil {
  41. return rv.(SomeType)
  42. }
  43. return nil
  44. }
  45. // SetMyKey sets a value for this package in the request values.
  46. func SetMyKey(r *http.Request, val SomeType) {
  47. context.Set(r, mykey, val)
  48. }
  49. Variables must be cleared at the end of a request, to remove all values
  50. that were stored. This can be done in an http.Handler, after a request was
  51. served. Just call Clear() passing the request:
  52. context.Clear(r)
  53. ...or use ClearHandler(), which conveniently wraps an http.Handler to clear
  54. variables at the end of a request lifetime.
  55. The Routers from the packages gorilla/mux and gorilla/pat call Clear()
  56. so if you are using either of them you don't need to clear the context manually.
  57. */
  58. package context