redis.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Package redis provides a redis interface for http caching.
  2. package redis
  3. import (
  4. "github.com/garyburd/redigo/redis"
  5. "github.com/gregjones/httpcache"
  6. )
  7. // cache is an implementation of httpcache.Cache that caches responses in a
  8. // redis server.
  9. type cache struct {
  10. redis.Conn
  11. }
  12. // cacheKey modifies an httpcache key for use in redis. Specifically, it
  13. // prefixes keys to avoid collision with other data stored in redis.
  14. func cacheKey(key string) string {
  15. return "rediscache:" + key
  16. }
  17. // Get returns the response corresponding to key if present.
  18. func (c cache) Get(key string) (resp []byte, ok bool) {
  19. item, err := redis.Bytes(c.Do("GET", cacheKey(key)))
  20. if err != nil {
  21. return nil, false
  22. }
  23. return item, true
  24. }
  25. // Set saves a response to the cache as key.
  26. func (c cache) Set(key string, resp []byte) {
  27. c.Do("SET", cacheKey(key), resp)
  28. }
  29. // Delete removes the response with key from the cache.
  30. func (c cache) Delete(key string) {
  31. c.Do("DEL", cacheKey(key))
  32. }
  33. // NewWithClient returns a new Cache with the given redis connection.
  34. func NewWithClient(client redis.Conn) httpcache.Cache {
  35. return cache{client}
  36. }