forked from gregjones/httpcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
45 lines (38 loc) · 1.19 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
// Package redis provides a redis interface for http caching.
package redis
import (
"github.com/gomodule/redigo/redis"
"github.com/secure-cloud-stack/httpcache"
)
// cache is an implementation of httpcache.Cache that caches responses in a
// redis server.
type cache struct {
redis.Conn
}
// cacheKey modifies an httpcache key for use in redis. Specifically, it
// prefixes keys to avoid collision with other data stored in redis.
func cacheKey(key string) string {
return "rediscache:" + key
}
// Get returns the response corresponding to key if present.
func (c cache) Get(key string) (resp []byte, ok bool, err error) {
item, err := redis.Bytes(c.Do("GET", cacheKey(key)))
if err != nil {
return nil, false, err
}
return item, true, nil
}
// Set saves a response to the cache as key.
func (c cache) Set(key string, resp []byte) error {
_, err := c.Do("SET", cacheKey(key), resp)
return err
}
// Delete removes the response with key from the cache.
func (c cache) Delete(key string) error {
_, err := c.Do("DEL", cacheKey(key))
return err
}
// NewWithClient returns a new Cache with the given redis connection.
func NewWithClient(client redis.Conn) httpcache.Cache {
return cache{client}
}