File tree Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Original file line number Diff line number Diff line change 1+ // Package redis provides a redis interface for http caching.
2+ package redis
3+
4+ import (
5+ "github.com/garyburd/redigo/redis"
6+ "github.com/gregjones/httpcache"
7+ )
8+
9+ // cache is an implementation of httpcache.Cache that caches responses in a
10+ // redis server.
11+ type cache struct {
12+ redis.Conn
13+ }
14+
15+ // cacheKey modifies an httpcache key for use in redis. Specifically, it
16+ // prefixes keys to avoid collision with other data stored in redis.
17+ func cacheKey (key string ) string {
18+ return "rediscache:" + key
19+ }
20+
21+ // Get returns the response corresponding to key if present.
22+ func (c cache ) Get (key string ) (resp []byte , ok bool ) {
23+ item , err := redis .Bytes (c .Do ("GET" , cacheKey (key )))
24+ if err != nil {
25+ return nil , false
26+ }
27+ return item , true
28+ }
29+
30+ // Set saves a response to the cache as key.
31+ func (c cache ) Set (key string , resp []byte ) {
32+ c .Do ("SET" , cacheKey (key ), resp )
33+ }
34+
35+ // Delete removes the response with key from the cache.
36+ func (c cache ) Delete (key string ) {
37+ c .Do ("DEL" , cacheKey (key ))
38+ }
39+
40+ // NewWithClient returns a new Cache with the given redis connection.
41+ func NewWithClient (client redis.Conn ) httpcache.Cache {
42+ return cache {client }
43+ }
Original file line number Diff line number Diff line change 1+ package redis
2+
3+ import (
4+ "bytes"
5+ "testing"
6+
7+ "github.com/garyburd/redigo/redis"
8+ )
9+
10+ func TestRedisCache (t * testing.T ) {
11+ conn , err := redis .Dial ("tcp" , "localhost:6379" )
12+ if err != nil {
13+ // TODO: rather than skip the test, fall back to a faked redis server
14+ t .Skipf ("skipping test; no server running at localhost:6379" )
15+ }
16+ conn .Do ("FLUSHALL" )
17+
18+ cache := NewWithClient (conn )
19+
20+ key := "testKey"
21+ _ , ok := cache .Get (key )
22+ if ok {
23+ t .Fatal ("retrieved key before adding it" )
24+ }
25+
26+ val := []byte ("some bytes" )
27+ cache .Set (key , val )
28+
29+ retVal , ok := cache .Get (key )
30+ if ! ok {
31+ t .Fatal ("could not retrieve an element we just added" )
32+ }
33+ if ! bytes .Equal (retVal , val ) {
34+ t .Fatal ("retrieved a different value than what we put in" )
35+ }
36+
37+ cache .Delete (key )
38+
39+ _ , ok = cache .Get (key )
40+ if ok {
41+ t .Fatal ("deleted key still present" )
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments