I'm writing a web application in Go but I have some troubles getting my code organized.
For basic CRUD operations on MongoDB I always have to do something like this in the beginning of my code:
session, err := mgo.Dial("localhost")
if err != nil {
return err
}
defer session.Close()
But I don't like the fact that I always have to repeat the same code.
Is there a way to make it shorter or to avoid a lot of this in my code:
if err != nil {
return err
}
I'm new to Go so maybe I'm missing something obvious.
First for the actual question, no, that's the Go away of checking for errors.
Second, the proper way to use mgo is to have one sesson and clone it every time you need to do something, for example:
var (
mgoSession *mgo.Session
)
func init() {
sess, err := mgo.Dial("localhost")
if err != nil {
panic(err) // no, not really
}
mgoSession = sess
}
func do_stuff_with_mgo() {
sess := mgoSession.Clone()
defer sess.Close()
//do stuff with sess
}
func main() {
go do_stuff_with_mgo()
go do_stuff_with_mgo()
do_stuff_with_mgo()
}
Also check this article about mgo (I'm not the author, but it helped me with learning mgo, it might be a bit outdated though.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With