Skip to content

Commit a12fa6c

Browse files
committed
Use sync.Map instead of locks
1 parent 3653f6f commit a12fa6c

File tree

1 file changed

+16
-20
lines changed

1 file changed

+16
-20
lines changed

Session.go

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,21 @@ import "sync"
55
// Session ...
66
type Session struct {
77
id string
8-
data map[string]interface{}
9-
lock sync.RWMutex
8+
data sync.Map
109
modified bool
1110
}
1211

1312
// New creates a new session with the given ID and data.
1413
func New(sid string, baseData map[string]interface{}) *Session {
15-
return &Session{
16-
id: sid,
17-
data: baseData,
14+
session := &Session{
15+
id: sid,
1816
}
17+
18+
for key, value := range baseData {
19+
session.data.Store(key, value)
20+
}
21+
22+
return session
1923
}
2024

2125
// ID returns the session ID.
@@ -25,9 +29,7 @@ func (session *Session) ID() string {
2529

2630
// Get returns the value for the key in this session.
2731
func (session *Session) Get(key string) interface{} {
28-
session.lock.RLock()
29-
value := session.data[key]
30-
session.lock.RUnlock()
32+
value, _ := session.data.Load(key)
3133
return value
3234
}
3335

@@ -50,15 +52,12 @@ func (session *Session) GetString(key string) string {
5052

5153
// Set sets the value for the key in this session.
5254
func (session *Session) Set(key string, value interface{}) {
53-
session.lock.Lock()
54-
5555
if value == nil {
56-
delete(session.data, key)
56+
session.data.Delete(key)
5757
} else {
58-
session.data[key] = value
58+
session.data.Store(key, value)
5959
}
6060

61-
session.lock.Unlock()
6261
session.modified = true
6362
}
6463

@@ -69,15 +68,12 @@ func (session *Session) Modified() bool {
6968

7069
// Data returns a copy of the underlying session data.
7170
func (session *Session) Data() map[string]interface{} {
72-
if session.data == nil {
73-
return nil
74-
}
75-
7671
newMap := map[string]interface{}{}
7772

78-
for key, value := range session.data {
79-
newMap[key] = value
80-
}
73+
session.data.Range(func(key, value interface{}) bool {
74+
newMap[key.(string)] = value
75+
return true
76+
})
8177

8278
return newMap
8379
}

0 commit comments

Comments
 (0)