Here is a snippet of my DAO implementation:
type (
User struct {
Name string `json:"name" bson:"name"`
...
}
UserDAO struct {
*mgo.Database
}
)
func NewUserDAO() (*UserDAO, error) {
session, err := mgo.Dial("mongodb://127.0.0.1:27017/test")
if err != nil {
return nil, err
}
return &UserDAO{session.DB("")}, nil
}
func (d *UserDAO) Insert(user User) error {
return d.C("users").Insert(user)
}
func (d *CandleDAO) Find(name string) ([]User, error) {
var result []User
if err := d.C("users").Find(bson.M{"name": name)}).Sort("time").All(&result); err != nil {
return nil, err
}
return result, nil
}
...
func (d *CandleDAO) Close() {
d.Session.Close()
}
And here is how I invoke it:
dao, err := dao.NewUserDAO()
if err != nil {
Log.Error(err.Error())
return
}
// close session... is this OK?
defer dao.Close()
users, err := dao.Find(&broker.Symbol{"BTC", "USD"}); if err != nil {
Log.Error(err.Error())
return
}
for i, user := range users {
fmt.Printf("%d ==> %v
", i, user)
}
The code above works... and my question is simple: shall I keep a global mgo.Database
instance or is it correct to always close the session when I'm finished and create a new one whenever I need?