Skip to content

Commit cb0d7de

Browse files
Add concurrency safe context option.
If SafeContext option set to true on an Echo server instance, contexts will be concurrent safe.
1 parent 6007218 commit cb0d7de

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

context.go

Lines changed: 10 additions & 0 deletions
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,18 @@ func (c *context) Cookies() []*http.Cookie {
360362
}
361363

362364
func (c *context) Get(key string) interface{} {
365+
if c.echo.SafeContext {
366+
c.lock.RLock()
367+
defer c.lock.RUnlock()
368+
}
363369
return c.store[key]
364370
}
365371

366372
func (c *context) Set(key string, val interface{}) {
373+
if c.echo.SafeContext {
374+
c.lock.Lock()
375+
defer c.lock.Unlock()
376+
}
367377
if c.store == nil {
368378
c.store = make(Map)
369379
}

context_test.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -390,12 +390,26 @@ func TestContextRedirect(t *testing.T) {
390390
}
391391

392392
func TestContextStore(t *testing.T) {
393-
var c Context
394-
c = new(context)
393+
e := &Echo{}
394+
395+
c := &context{
396+
echo: e,
397+
}
395398
c.Set("name", "Jon Snow")
396399
assert.Equal(t, "Jon Snow", c.Get("name"))
397400
}
398401

402+
func TestContextSafeStore(t *testing.T) {
403+
e := &Echo{}
404+
e.SafeContext = true
405+
406+
c := &context{
407+
echo: e,
408+
}
409+
c.Set("name", "Jon Safe")
410+
assert.Equal(t, "Jon Safe", c.Get("name"))
411+
}
412+
399413
func TestContextHandler(t *testing.T) {
400414
e := New()
401415
r := e.Router()

echo.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ type (
8484
Validator Validator
8585
Renderer Renderer
8686
Logger Logger
87+
SafeContext bool
8788
}
8889

8990
// Route contains a handler and information for matching against requests.

0 commit comments

Comments
 (0)