Skip to content

Commit

Permalink
Add KeepContext flag to Router to disable clearing of context data.
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnadratowski authored and kisielk committed Jul 10, 2013
1 parent 9b36453 commit e718e93
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
8 changes: 6 additions & 2 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

// NewRouter returns a new router instance.
func NewRouter() *Router {
return &Router{namedRoutes: make(map[string]*Route)}
return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
}

// Router registers routes to be matched and dispatches a handler.
Expand Down Expand Up @@ -46,6 +46,8 @@ type Router struct {
namedRoutes map[string]*Route
// See Router.StrictSlash(). This defines the flag for new routes.
strictSlash bool
// If true, do not clear the the request context after handling the request
KeepContext bool
}

// Match matches registered routes against the request.
Expand Down Expand Up @@ -82,7 +84,9 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
handler = r.NotFoundHandler
}
defer context.Clear(req)
if !r.KeepContext {
defer context.Clear(req)
}
handler.ServeHTTP(w, req)
}

Expand Down
32 changes: 32 additions & 0 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"fmt"
"net/http"
"testing"

"github.com/gorilla/context"
)

type routeTest struct {
Expand Down Expand Up @@ -656,6 +658,36 @@ func testRoute(t *testing.T, test routeTest) {
}
}

// 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")
}

}

// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW
func TestSubrouterHeader(t *testing.T) {
expected := "func1 response"
Expand Down

0 comments on commit e718e93

Please sign in to comment.