-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
90 lines (79 loc) · 1.67 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package coreredis
import (
"crypto/tls"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"github.com/go-redis/redis"
)
const (
// DefaultURL is the default redis host url.
DefaultURL = "redis://127.0.0.1:6379/0"
)
// ConfigError happens when the redis connection cannot be configured.
type ConfigError struct {
msg interface{}
}
func (e ConfigError) Error() string {
return fmt.Sprintf("redis config error: %v", e.msg)
}
// URLFromEnv tries to retrieve the redis url from the environment.
func URLFromEnv() string {
url := os.Getenv("REDIS_URL")
if url == "" {
url = os.Getenv("REDIS_HOST")
}
if url == "" {
url = DefaultURL
}
return url
}
// Parse attempts to parse a redis url and return options.
func Parse(s string) (*redis.Options, error) {
rurl, err := url.Parse(s)
if err != nil {
return nil, ConfigError{err}
}
pass, ok := rurl.User.Password()
if !ok {
pass = rurl.User.Username()
}
var db int
path := strings.Split(strings.TrimPrefix(rurl.Path, "/"), "/")
if len(path) > 1 {
if path[0] != "" {
n, err := strconv.Atoi(path[0])
if err != nil {
return nil, ConfigError{err}
}
db = n
}
}
opt := &redis.Options{
Addr: rurl.Host,
Password: pass,
DB: db,
}
switch rurl.Scheme {
case "rediss":
opt.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
return opt, nil
}
// NewDefaultClient returns a wrapped redis client with default configuration.
func NewDefaultClient() *Client {
opt, err := Parse(URLFromEnv())
if err != nil {
log.Fatalln(err)
}
return NewClient(opt)
}
// NewClient returns a wrapped redis client.
func NewClient(opt *redis.Options) *Client {
return &Client{redis.NewClient(opt)}
}