Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize Go code for CRUD operations on MongoDB

Tags:

go

mgo

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.

like image 463
roeland Avatar asked Aug 02 '14 21:08

roeland


1 Answers

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.)

like image 115
OneOfOne Avatar answered Oct 05 '22 18:10

OneOfOne