diff --git a/context.go b/context.go index d4722700..75f59fd4 100644 --- a/context.go +++ b/context.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "strings" + "sync" ) type ( @@ -198,6 +199,7 @@ type ( handler HandlerFunc store Map echo *Echo + lock sync.RWMutex } ) @@ -360,10 +362,15 @@ func (c *context) Cookies() []*http.Cookie { } func (c *context) Get(key string) interface{} { + c.lock.RLock() + defer c.lock.RUnlock() return c.store[key] } func (c *context) Set(key string, val interface{}) { + c.lock.Lock() + defer c.lock.Unlock() + if c.store == nil { c.store = make(Map) } @@ -597,4 +604,3 @@ func (c *context) Reset(r *http.Request, w http.ResponseWriter) { // NOTE: Don't reset because it has to have length c.echo.maxParam at all times // c.pvalues = nil } - diff --git a/context_test.go b/context_test.go index 3a47364d..6118866f 100644 --- a/context_test.go +++ b/context_test.go @@ -529,6 +529,21 @@ func TestContextStore(t *testing.T) { testify.Equal(t, "Jon Snow", c.Get("name")) } +func BenchmarkContext_Store(b *testing.B) { + e := &Echo{} + + c := &context{ + echo: e, + } + + for n := 0; n < b.N; n++ { + c.Set("name", "Jon Snow") + if c.Get("name") != "Jon Snow" { + b.Fail() + } + } +} + func TestContextHandler(t *testing.T) { e := New() r := e.Router() @@ -543,4 +558,3 @@ func TestContextHandler(t *testing.T) { c.Handler()(c) testify.Equal(t, "handler", b.String()) } -