6

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
roeland
  • 6,058
  • 7
  • 50
  • 67

1 Answers1

3

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

roeland
  • 6,058
  • 7
  • 50
  • 67
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • You never call the init(), but I get the idea. Good article. Thanks. – roeland Aug 02 '14 at 21:55
  • init is automatically called by Go before main. Check [Package_initialization](http://golang.org/ref/spec#Package_initialization) in the specs. – OneOfOne Aug 02 '14 at 21:57
  • The article linked in the answer is no longer available (404), wish I could still read it. – Ajay M Apr 20 '17 at 13:48
  • 1
    This seems to be the new link: http://denis.papathanasiou.org/posts/2012.10.14.post.html. I edited the post. – roeland Nov 20 '17 at 20:51