-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis.go
94 lines (79 loc) · 2.02 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
91
92
93
94
/*
Redis utility functions for GoPics.
Copyright (c) 2015, Luca Chiricozzi. All rights reserved.
Released under the MIT License.
http://opensource.org/licenses/MIT
*/
package main
import (
"time"
"github.com/garyburd/redigo/redis"
)
const (
redisMaxIdle = 3
redisDefaultAddr = ":6379"
)
var redisIdleTimeout = 240 * time.Second
// newPool creates a new connections pool for concurrent access
// to Redis.
func newPool(server string) *redis.Pool {
return &redis.Pool{
MaxIdle: redisMaxIdle,
IdleTimeout: redisIdleTimeout,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
// redisFlat flatens a struct for Redis HMSET
func redisFlat(key string, value interface{}) redis.Args {
return redis.Args{}.Add(key).AddFlat(value)
}
// redisGetUser search for an user with the given username,
// it returns the user data if the user is found, otherwise,
// it returns a redis.ErrNil.
func redisGetUser(conn redis.Conn, username string) (*User, error) {
val, err := redis.Values(conn.Do("HGETALL", userTag+username))
switch {
case err != nil:
return nil, err
case len(val) == 0:
return nil, redis.ErrNil
}
usr := new(User)
err = redis.ScanStruct(val, usr)
if err != nil {
return nil, err
}
return usr, nil
}
// redisGetPosts return a list of the latest one hundred posts in postSet.
// Posts are sorted by publishing date, starting from the latest one.
func redisGetPosts(conn redis.Conn, postSet string) ([]Post, error) {
postNames, err := redis.Strings(conn.Do("ZREVRANGE", postSet, 0, 100))
if err != nil {
return nil, err
}
posts := []Post{}
for _, name := range postNames {
val, err := redis.Values(conn.Do("HGETALL", postTag+name))
if err != nil {
return nil, err
}
p := new(Post)
err = redis.ScanStruct(val, p)
if err != nil {
return nil, err
}
posts = append(posts, *p)
}
return posts, nil
}