-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
52 lines (46 loc) · 1.26 KB
/
db.go
File metadata and controls
52 lines (46 loc) · 1.26 KB
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
package main
import (
"github.com/garyburd/redigo/redis"
"github.com/pkg/errors"
)
type DB interface {
get(field string) (string, error)
close() error
}
type Redis struct {
conn redis.Conn
hashKey string
}
func newRedis(host, port, defaultDestURL, hashKey string) (DB, error) {
c, err := redis.Dial("tcp", host+":"+port)
if err != nil {
return nil, errors.Wrap(err, "Failed start connection to Redis")
}
_, err = c.Do("HSET", hashKey, "default", defaultDestURL)
if err != nil {
return nil, errors.Wrapf(err, "Failed Redis Command 'HSET %s default %s'", hashKey, defaultDestURL)
}
r := &Redis{
conn: c,
hashKey: hashKey,
}
return r, nil
}
// If the field does not exist, then the return value is the value of the "default" key
func (r *Redis) get(field string) (string, error) {
reply, err := redis.String(r.conn.Do("HGET", r.hashKey, field))
switch {
case err == redis.ErrNil: // when the field not exist field
reply, _ = redis.String(r.conn.Do("HGET", r.hashKey, "default"))
case err != nil:
return "", errors.Wrapf(err, "Failed Redis Command 'HGET %s %s'", r.hashKey, field)
}
return reply, nil
}
func (r *Redis) close() error {
err := r.conn.Close()
if err != nil {
return errors.Wrap(err, "Failed close connection to Redis")
}
return nil
}