1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-12 01:22:21 +02:00

Use concurrency safe context by default. (#1158)

This commit is contained in:
Andrei Avram 2019-02-12 20:56:26 +02:00 committed by Vishal Rana
parent 88965757af
commit 3d73323154
2 changed files with 22 additions and 2 deletions

View File

@ -13,6 +13,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
) )
type ( type (
@ -198,6 +199,7 @@ type (
handler HandlerFunc handler HandlerFunc
store Map store Map
echo *Echo echo *Echo
lock sync.RWMutex
} }
) )
@ -360,10 +362,15 @@ func (c *context) Cookies() []*http.Cookie {
} }
func (c *context) Get(key string) interface{} { func (c *context) Get(key string) interface{} {
c.lock.RLock()
defer c.lock.RUnlock()
return c.store[key] return c.store[key]
} }
func (c *context) Set(key string, val interface{}) { func (c *context) Set(key string, val interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
if c.store == nil { if c.store == nil {
c.store = make(Map) 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 // NOTE: Don't reset because it has to have length c.echo.maxParam at all times
// c.pvalues = nil // c.pvalues = nil
} }

View File

@ -529,6 +529,21 @@ func TestContextStore(t *testing.T) {
testify.Equal(t, "Jon Snow", c.Get("name")) 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) { func TestContextHandler(t *testing.T) {
e := New() e := New()
r := e.Router() r := e.Router()
@ -543,4 +558,3 @@ func TestContextHandler(t *testing.T) {
c.Handler()(c) c.Handler()(c)
testify.Equal(t, "handler", b.String()) testify.Equal(t, "handler", b.String())
} }