Skip to content

Commit a91ca8c

Browse files
Use concurrency safe context by default.
1 parent 8896575 commit a91ca8c

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

context.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"os"
1414
"path/filepath"
1515
"strings"
16+
"sync"
1617
)
1718

1819
type (
@@ -198,6 +199,7 @@ type (
198199
handler HandlerFunc
199200
store Map
200201
echo *Echo
202+
lock sync.RWMutex
201203
}
202204
)
203205

@@ -360,10 +362,15 @@ func (c *context) Cookies() []*http.Cookie {
360362
}
361363

362364
func (c *context) Get(key string) interface{} {
365+
c.lock.RLock()
366+
defer c.lock.RUnlock()
363367
return c.store[key]
364368
}
365369

366370
func (c *context) Set(key string, val interface{}) {
371+
c.lock.Lock()
372+
defer c.lock.Unlock()
373+
367374
if c.store == nil {
368375
c.store = make(Map)
369376
}
@@ -597,4 +604,3 @@ func (c *context) Reset(r *http.Request, w http.ResponseWriter) {
597604
// NOTE: Don't reset because it has to have length c.echo.maxParam at all times
598605
// c.pvalues = nil
599606
}
600-

context_test.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,21 @@ func TestContextStore(t *testing.T) {
529529
testify.Equal(t, "Jon Snow", c.Get("name"))
530530
}
531531

532+
func BenchmarkContext_Store(b *testing.B) {
533+
e := &Echo{}
534+
535+
c := &context{
536+
echo: e,
537+
}
538+
539+
for n := 0; n < b.N; n++ {
540+
c.Set("name", "Jon Snow")
541+
if c.Get("name") != "Jon Snow" {
542+
b.Fail()
543+
}
544+
}
545+
}
546+
532547
func TestContextHandler(t *testing.T) {
533548
e := New()
534549
r := e.Router()
@@ -543,4 +558,3 @@ func TestContextHandler(t *testing.T) {
543558
c.Handler()(c)
544559
testify.Equal(t, "handler", b.String())
545560
}
546-

0 commit comments

Comments
 (0)