...

Source file src/github.com/gregjones/httpcache/memcache/appengine.go

Documentation: github.com/gregjones/httpcache/memcache

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

View as plain text