Skip to content

Commit a830c4c

Browse files
committed
Add a redis session handler
1 parent ab623dd commit a830c4c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

session/redis-handler.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package session
2+
3+
import (
4+
"encoding/json"
5+
"github.com/gomodule/redigo/redis"
6+
"time"
7+
)
8+
9+
type RedisHandler struct {
10+
pool *redis.Pool // redis connection pool
11+
prefix string
12+
lifetime time.Duration
13+
}
14+
15+
// NewRedisHandler Create a redis session handler
16+
func NewRedisHandler(pool *redis.Pool, prefix string, lifetime time.Duration) *RedisHandler {
17+
return &RedisHandler{pool, prefix, lifetime}
18+
}
19+
20+
func (rh *RedisHandler) Read(id string) string {
21+
c := rh.pool.Get()
22+
defer c.Close()
23+
24+
b, err := redis.Bytes(c.Do("GET", rh.prefix+":"+id))
25+
if err != nil {
26+
return ""
27+
}
28+
29+
var value string
30+
31+
json.Unmarshal(b, value)
32+
33+
return value
34+
}
35+
36+
func (rh *RedisHandler) Write(id string, data string) {
37+
c := rh.pool.Get()
38+
defer c.Close()
39+
40+
c.Do("SETEX", rh.prefix+":"+id, int64(rh.lifetime), data)
41+
}

0 commit comments

Comments
 (0)