6 changed files with 102 additions and 48 deletions
@ -0,0 +1,26 @@
@@ -0,0 +1,26 @@
|
||||
// +build !go1.7
|
||||
|
||||
package mux |
||||
|
||||
import ( |
||||
"net/http" |
||||
|
||||
"github.com/gorilla/context" |
||||
) |
||||
|
||||
func contextGet(r *http.Request, key interface{}) interface{} { |
||||
return context.Get(r, key) |
||||
} |
||||
|
||||
func contextSet(r *http.Request, key, val interface{}) *http.Request { |
||||
if val == nil { |
||||
return r |
||||
} |
||||
|
||||
context.Set(r, key, val) |
||||
return r |
||||
} |
||||
|
||||
func contextClear(r *http.Request) { |
||||
context.Clear(r) |
||||
} |
||||
@ -0,0 +1,40 @@
@@ -0,0 +1,40 @@
|
||||
// +build !go1.7
|
||||
|
||||
package mux |
||||
|
||||
import ( |
||||
"net/http" |
||||
"testing" |
||||
|
||||
"github.com/gorilla/context" |
||||
) |
||||
|
||||
// Tests that the context is cleared or not cleared properly depending on
|
||||
// the configuration of the router
|
||||
func TestKeepContext(t *testing.T) { |
||||
func1 := func(w http.ResponseWriter, r *http.Request) {} |
||||
|
||||
r := NewRouter() |
||||
r.HandleFunc("/", func1).Name("func1") |
||||
|
||||
req, _ := http.NewRequest("GET", "http://localhost/", nil) |
||||
context.Set(req, "t", 1) |
||||
|
||||
res := new(http.ResponseWriter) |
||||
r.ServeHTTP(*res, req) |
||||
|
||||
if _, ok := context.GetOk(req, "t"); ok { |
||||
t.Error("Context should have been cleared at end of request") |
||||
} |
||||
|
||||
r.KeepContext = true |
||||
|
||||
req, _ = http.NewRequest("GET", "http://localhost/", nil) |
||||
context.Set(req, "t", 1) |
||||
|
||||
r.ServeHTTP(*res, req) |
||||
if _, ok := context.GetOk(req, "t"); !ok { |
||||
t.Error("Context should NOT have been cleared at end of request") |
||||
} |
||||
|
||||
} |
||||
@ -0,0 +1,24 @@
@@ -0,0 +1,24 @@
|
||||
// +build go1.7
|
||||
|
||||
package mux |
||||
|
||||
import ( |
||||
"context" |
||||
"net/http" |
||||
) |
||||
|
||||
func contextGet(r *http.Request, key interface{}) interface{} { |
||||
return r.Context().Value(key) |
||||
} |
||||
|
||||
func contextSet(r *http.Request, key, val interface{}) *http.Request { |
||||
if val == nil { |
||||
return r |
||||
} |
||||
|
||||
return r.WithContext(context.WithValue(r.Context(), key, val)) |
||||
} |
||||
|
||||
func contextClear(r *http.Request) { |
||||
return |
||||
} |
||||
Loading…
Reference in new issue