Created
January 17, 2018 12:58
-
-
Save codingconcepts/78c10f43a3292587b45a56ade75aff35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
mgo "gopkg.in/mgo.v2" | |
"gopkg.in/mgo.v2/bson" | |
) | |
const ( | |
db = "db" | |
personCollection = "person" | |
) | |
func main() { | |
session, err := mgo.Dial("127.0.0.1:27017") | |
if err != nil { | |
log.Fatalf("error dialling mongodb: %v", err) | |
} | |
defer session.Close() | |
repo := newMongoPersonRepository(session.Copy()) | |
if err = repo.create(&person{Name: "Dan", Age: 21}); err != nil { | |
log.Fatalf("error inserting person: %v", err) | |
} | |
person, err := repo.find("Dan") | |
if err != nil { | |
log.Fatalf("error finding person: %v", err) | |
} | |
fmt.Println(person) | |
if err = session.DB(db).DropDatabase(); err != nil { | |
log.Fatalf("error dropping database: %v", err) | |
} | |
} | |
type person struct { | |
Name string `bson:"name"` | |
Age int `bson:"age"` | |
} | |
type personRepository interface { | |
find(name string) (p *person, err error) | |
create(p *person) (err error) | |
} | |
type mongoPersonRepository struct { | |
session *mgo.Session | |
} | |
func newMongoPersonRepository(session *mgo.Session) *mongoPersonRepository { | |
return &mongoPersonRepository{ | |
session: session, | |
} | |
} | |
func (r *mongoPersonRepository) find(name string) (p person, err error) { | |
err = r.session.DB(db).C(personCollection).Find(bson.M{"name": name}).One(&p) | |
return | |
} | |
func (r *mongoPersonRepository) create(p *person) (err error) { | |
err = r.session.DB(db).C(personCollection).Insert(p) | |
return | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
) | |
func TestPersonRepository(t *testing.T) { | |
p := &person{Name: "Dan", Age: 21} | |
r := newMockPersonRepository(nil) | |
t.Log(r.create(p)) | |
t.Log(r.find("Dan")) | |
} | |
type mockPersonRepository struct { | |
person *person | |
err error | |
} | |
func newMockPersonRepository(err error) *mockPersonRepository { | |
return &mockPersonRepository{ | |
err: err, | |
} | |
} | |
func (r *mockPersonRepository) find(name string) (p *person, err error) { | |
return r.person, r.err | |
} | |
func (r *mockPersonRepository) create(p *person) (err error) { | |
r.person = p | |
return r.err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment