Skip to content

Instantly share code, notes, and snippets.

@spdrman
Created January 2, 2020 03:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spdrman/02a9bd0d0fa3dd55a004b1ee5b8349d5 to your computer and use it in GitHub Desktop.
Save spdrman/02a9bd0d0fa3dd55a004b1ee5b8349d5 to your computer and use it in GitHub Desktop.
golang pattern for database access with cache layer
type Store interface {
GetFollowers(userID string) ([]models.User, error)
}
type DatabaseStore struct {
// wrap sql connection
// or any other driver that your database needs
}
func (s *DatabaseStore) GetFollowers(userID string) ([]models.User, error) {
// get users from db
// can be any db, e.g. PostgreSQL, CouchDB, MongoDB
return users, nil
}
type CacheStore struct {
// embed any other store
// this also makes unimplemented store methods just pass through
Store
// cache internals
}
func (s *CacheStore) GetFollowers(userID string) ([]models.User, error) {
// return user from cache if it's there
// if not, get from underlying store
user, err = s.Store.GetFollowers(userID)
// error check
// add user to cache
return users, nil
}
// easily instantiate any configuration you need
store := CacheStore{DatabaseStore{DB: db}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment