memcache.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // +build !appengine
  2. // Package memcache provides an implementation of httpcache.Cache that uses
  3. // gomemcache to store cached responses.
  4. //
  5. // When built for Google App Engine, this package will provide an
  6. // implementation that uses App Engine's memcache service. See the
  7. // appengine.go file in this package for details.
  8. package memcache
  9. import (
  10. "github.com/bradfitz/gomemcache/memcache"
  11. )
  12. // Cache is an implementation of httpcache.Cache that caches responses in a
  13. // memcache server.
  14. type Cache struct {
  15. *memcache.Client
  16. }
  17. // cacheKey modifies an httpcache key for use in memcache. Specifically, it
  18. // prefixes keys to avoid collision with other data stored in memcache.
  19. func cacheKey(key string) string {
  20. return "httpcache:" + key
  21. }
  22. // Get returns the response corresponding to key if present.
  23. func (c *Cache) Get(key string) (resp []byte, ok bool) {
  24. item, err := c.Client.Get(cacheKey(key))
  25. if err != nil {
  26. return nil, false
  27. }
  28. return item.Value, true
  29. }
  30. // Set saves a response to the cache as key.
  31. func (c *Cache) Set(key string, resp []byte) {
  32. item := &memcache.Item{
  33. Key: cacheKey(key),
  34. Value: resp,
  35. }
  36. c.Client.Set(item)
  37. }
  38. // Delete removes the response with key from the cache.
  39. func (c *Cache) Delete(key string) {
  40. c.Client.Delete(cacheKey(key))
  41. }
  42. // New returns a new Cache using the provided memcache server(s) with equal
  43. // weight. If a server is listed multiple times, it gets a proportional amount
  44. // of weight.
  45. func New(server ...string) *Cache {
  46. return NewWithClient(memcache.New(server...))
  47. }
  48. // NewWithClient returns a new Cache with the given memcache client.
  49. func NewWithClient(client *memcache.Client) *Cache {
  50. return &Cache{client}
  51. }