Skip to content

Instantly share code, notes, and snippets.

@balintsera
Last active August 28, 2016 06:47
Show Gist options
  • Save balintsera/8e3be29834a5f0ba7d599927569b6cc4 to your computer and use it in GitHub Desktop.
Save balintsera/8e3be29834a5f0ba7d599927569b6cc4 to your computer and use it in GitHub Desktop.
package main
import mgo "gopkg.in/mgo.v2"
// Persist is a persisting dependency
type Persist interface {
Insert() (err error)
Update() (err error)
Remove() (err error)
}
// Mongo is a concrete Persist example
type Mongo struct {
collection *mgo.Collection
}
func init() {
// Mongo.SetCollection()
}
// Insert an object to the collection
func (mongo *Mongo) Insert() (err error) {
err = mongo.collection.Insert()
return
}
// Insert an object to the collection
func (mongo *Mongo) Update() (err error) {
//err = mongo.collection.Update()
return err
}
// Insert an object to the collection
func (mongo *Mongo) Remove() (err error) {
err = mongo.collection.Remove()
return err
}
// private because we have to use a factory like pattern as a "constructor"
type user struct {
Persist Persist // inject as dependency?
name string
mail string
}
// Insert
func (userObject user) Insert() (err error) {
err = userObject.Persist.Insert()
return
}
// User is a constructor like construct with optional parameters (as function)
func User(options ...func(*user) error) *user {
userObject := new(user)
// Run the options that in turn can set any public property
for _, function := range options {
// function shuold set something
function(userObject)
}
// Persistence is mandatory set the default if not set via option function
if userObject.Persist == nil {
userObject.Persist = new(Mongo)
}
return userObject
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment