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