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