Skip to content

Instantly share code, notes, and snippets.

@shazow
Created September 3, 2013 19:25
Show Gist options
  • Save shazow/6428419 to your computer and use it in GitHub Desktop.
Save shazow/6428419 to your computer and use it in GitHub Desktop.
Caching with Go
// Without caching, or with a memoization wrapper:
func (c *Context) FooApi() (*Result, error) {
return c.apiClient.someGoogleApiQuery.Do()
}
func (c *Context) BarApi(someArg string) (*Result, error) {
return c.apiClient.someGoogleApiQuery.Filter(someArg).Do()
}
// With explicit caching
func (c *Context) FooApiCached() (r *Result, err error) {
key := "FooApi"
_, err = memcache.Gob.Get(c, key, r)
if err == nil {
return r, nil
}
r, err = c.apiClient.someGoogleApiQuery.Do()
if err != nil {
return r, err
}
memcache.Gob.Set(c, &memcache.Item{
Key: key,
Object: r,
})
return r, nil
}
func (c *Context) BarApiCached(someArg string) (r *Result, err error) {
key := "BarApi:" + someArg
_, err = memcache.Gob.Get(c, key, r)
if err == nil {
return r, nil
}
r, err = c.apiClient.someGoogleApiQuery.Filter(someArg).Do()
if err != nil {
return r, err
}
memcache.Gob.Set(c, &memcache.Item{
Key: key,
Object: r,
})
return r, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment