appengine.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // +build appengine
  2. // Package memcache provides an implementation of httpcache.Cache that uses App
  3. // Engine's memcache package to store cached responses.
  4. //
  5. // When not built for Google App Engine, this package will provide an
  6. // implementation that connects to a specified memcached server. See the
  7. // memcache.go file in this package for details.
  8. package memcache
  9. import (
  10. "appengine"
  11. "appengine/memcache"
  12. )
  13. // Cache is an implementation of httpcache.Cache that caches responses in App
  14. // Engine's memcache.
  15. type Cache struct {
  16. appengine.Context
  17. }
  18. // cacheKey modifies an httpcache key for use in memcache. Specifically, it
  19. // prefixes keys to avoid collision with other data stored in memcache.
  20. func cacheKey(key string) string {
  21. return "httpcache:" + key
  22. }
  23. // Get returns the response corresponding to key if present.
  24. func (c *Cache) Get(key string) (resp []byte, ok bool) {
  25. item, err := memcache.Get(c.Context, cacheKey(key))
  26. if err != nil {
  27. if err != memcache.ErrCacheMiss {
  28. c.Context.Errorf("error getting cached response: %v", err)
  29. }
  30. return nil, false
  31. }
  32. return item.Value, true
  33. }
  34. // Set saves a response to the cache as key.
  35. func (c *Cache) Set(key string, resp []byte) {
  36. item := &memcache.Item{
  37. Key: cacheKey(key),
  38. Value: resp,
  39. }
  40. if err := memcache.Set(c.Context, item); err != nil {
  41. c.Context.Errorf("error caching response: %v", err)
  42. }
  43. }
  44. // Delete removes the response with key from the cache.
  45. func (c *Cache) Delete(key string) {
  46. if err := memcache.Delete(c.Context, cacheKey(key)); err != nil {
  47. c.Context.Errorf("error deleting cached response: %v", err)
  48. }
  49. }
  50. // New returns a new Cache for the given context.
  51. func New(ctx appengine.Context) *Cache {
  52. return &Cache{ctx}
  53. }