Organize Go code for CRUD operations on MongoDB

I am writing a web application in Go, but I have some problems with creating my code.
For basic CRUD operations in MongoDB, I always need to do something like this at the beginning of my code:

session, err := mgo.Dial("localhost") if err != nil { return err } defer session.Close() 

But I do not like the fact that I always have to repeat the same code.

Is there a way to make this shorter or avoid this in my code:

 if err != nil { return err } 

I'm new to Go, maybe I'm missing something obvious.

+6
source share
1 answer

At first, for the actual question, there is no way out of error checking.

Secondly, the correct 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 out this article on mgo (I'm not an author, but it helped me learn mgo, it might be a bit dated, though.)

+3
source

Source: https://habr.com/ru/post/973269/


All Articles