-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
72 lines (59 loc) · 1.31 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package goroku
import (
"fmt"
"log"
"net/url"
"os"
"golang.org/x/net/context"
"gopkg.in/redis.v2"
)
type redisDB string
func MustRedis(ctx context.Context) (*redis.Client) {
db, ok := Redis(ctx)
if !ok {
panic("not found redis")
}
return db
}
func Redis(ctx context.Context) (*redis.Client, bool) {
key := redisDB("default")
db, ok := ctx.Value(key).(*redis.Client)
return db, ok
}
func OpenRedis(ctx context.Context) context.Context {
addr, password := GetHerokuRedisAddr()
client := redis.NewTCPClient(&redis.Options{
Addr: addr,
Password: password,
})
ctx = context.WithValue(ctx, redisDB("default"), client)
return ctx
}
func GetHerokuRedisAddr() (addr string, password string) {
addr = fmt.Sprintf("%s:%d", "localhost", 6379)
password = ""
redisURL := os.Getenv("REDISTOGO_URL")
if redisURL == "" {
fmt.Println("local: redis", addr, password)
return
}
redisInfo, err := url.Parse(redisURL)
if err != nil {
return
}
addr = redisInfo.Host
if redisInfo.User != nil {
password, _ = redisInfo.User.Password()
}
return
}
func CloseRedis(ctx context.Context) context.Context {
client, _ := Redis(ctx)
if client == nil {
return ctx
}
if err := client.Close(); err != nil {
log.Println("redis close error:", err)
}
return context.WithValue(ctx, redisDB("default"), nil)
}