Skip to content

Instantly share code, notes, and snippets.

@alvintamie
Last active July 11, 2018 20:07
Show Gist options
  • Save alvintamie/d3bf0fdeb401d394fbbb94abfc80f466 to your computer and use it in GitHub Desktop.
Save alvintamie/d3bf0fdeb401d394fbbb94abfc80f466 to your computer and use it in GitHub Desktop.
caching idea go
func Cache(key string, expirationTime int, f func() (interface{}, error)) (interface{}, error) {
logger.Info("Check caching if exist return the result immediately")
q, e := f()
logger.Info("Set result to cache")
return q, e
}
func (r *repository) ResolveQuestionSetBySerials(serials []string) (*[]RubelQuestionSet, error) {
questionSets, err := Cache("Test", 100, func() (interface{}, error) {
// this part used to resolve the records
session := r.session.Clone()
c := session.DB("xxx").C("xxxxx")
questionSets := []RubelQuestionSet{}
err := c.Find(bson.M{"serial": bson.M{"$in": serials}}).All(&questionSets)
if err != nil {
return nil, err
}
return &questionSets, err
})
if err != nil {
// handle error
return nil, err
}
// however still need to do casting
return questionSets.(*[]RubelQuestionSet), err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment