组织Go代码以进行对MongoDB的CRUD操作

huangapple go评论85阅读模式
英文:

Organize Go code for CRUD operations on MongoDB

问题

我正在使用Go编写一个Web应用程序,但是在组织我的代码方面遇到了一些问题。
对于MongoDB上的基本CRUD操作,我总是不得不在代码的开头做这样的事情:

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

但我不喜欢我总是不得不重复相同的代码这一事实。

有没有办法让它变得更短,或者避免在我的代码中大量使用这种代码:

if err != nil {
	return err
}

我是Go的新手,所以也许我漏掉了一些显而易见的东西。

英文:

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.

答案1

得分: 3

首先,对于实际的问题,不,那是检查错误的方法。

其次,正确使用mgo的方法是每次需要执行操作时都要有一个会话并进行克隆,例如:

var (
    mgoSession *mgo.Session
)

func init() {
    sess, err := mgo.Dial("localhost")
    if err != nil {
        panic(err) // 不,真的不要这样做
    }
    mgoSession = sess
}

func do_stuff_with_mgo() {
    sess := mgoSession.Clone()
    defer sess.Close()
    // 使用sess进行操作
}

func main() {
    go do_stuff_with_mgo()
    go do_stuff_with_mgo()
    do_stuff_with_mgo()
}

另外,可以参考这篇文章了解有关mgo的更多信息(我不是作者,但它帮助我学习mgo,尽管可能有点过时)。

英文:

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

huangapple
  • 本文由 发表于 2014年8月3日 05:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/25099598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定