在代码中的多个位置如何传递 *sql.DB 变量?

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

How should I pass around the *sql.DB variable in several places in the code?

问题

我读到了你不应该关闭 *sql.DB 变量的建议。

http://go-database-sql.org/accessing.html

它还说我应该:"根据需要传递它,或者以某种方式全局可用,但保持它处于打开状态。"

但是这篇文章说我不应该使用全局变量,而应该使用闭包:
https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091

我在这里找到了一个闭包的例子:
https://gist.github.com/tsenart/5fc18c659814c078378d

我的问题是:我应该如何将这个变量传递给不同的包?

例如,如果我有一个名为 User 的包,像这样:

package user

import "errors"

var userNotFound = errors.New("User was not found.")

// 我应该将 sql.DB 的指针作为 User 类型的属性吗?
type User struct {
    // db *sql.DB
    Id       int
    Email    string
    Username string
}

// 我应该在函数中将 *sql.DB 作为参数传入吗?
func FindById(id int) (*User, error) {
    // 以某种方式访问 *sql.DB

    // 进行查询并查看是否找到了具有该 id 的用户

    // 如果找不到用户,我应该返回一个错误吗?
    return &User{}, nil
}

那么我应该将 sql.DB 的指针作为 User 类型的属性吗?
还是应该在 findById 方法中传递一个指针?

如果我想通过用户的 id 查找用户,我应该如何在下面的 main 函数中完成所有这些操作?

func getUserById(db *sql.DB) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        fmt.Fprint(w, ps.ByName("id"))

        // 我将在这里创建一个新的(User),我应该如何在 user 包中使用 *sql.DB?
    }
}

func main() {

    dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s?charset=utf8",
        cfg.DbUser, cfg.DbPass, cfg.DbProtocol, cfg.DbAddress, cfg.DbPort, cfg.DbName)

    db, err := sql.Open("mysql", dsn)
    err = db.Ping()
    if err != nil {
        log.Fatal(err)
    }

    router := httprouter.New()
    router.GET("/api/user/:id", getUserById(db))
    router.NotFound = &DefaultHandler{}
    log.Fatal(http.ListenAndServe(":8080", router))
}

我应该如何做?有什么好的首选方式或最佳实践吗?

英文:

I read that you should not close the *sql.DB variable.

http://go-database-sql.org/accessing.html

And it also says that I should: "Pass it around as needed, or make it available somehow globally, but keep it open."

But this article says I should not use global variables but should use closures:
https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091

I found an example of closure here:
https://gist.github.com/tsenart/5fc18c659814c078378d

My question is: How should I pass around this variable to different packages?

For example if I have a package called User like this:

package user

import "errors"

var userNotFound = errors.New("User was not found.")

// Should I have a pointer to sql.DB as a property of the User type?
type User struct {
	// db *sql.DB
	Id       int
	Email    string
	Username string
}

// Should I pass in *sql.DB as parameter in the function?
func FindById(id int) (*User, error) {
	// Access *sql.DB somehow

	// Do query and look if user with id is found

	// Should I return an error if the user is not found?
	return &User{}, nil
}

Should I then have a pointer to sql.DB as property of the User type?
Or should I pass a pointer to it in the findById method?

If I want to find a user by it's id, how should I do all this from a main function like below?

func getUserById(db *sql.DB) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		fmt.Fprint(w, ps.ByName("id"))

		// I will create a new(User) here, how should I use the *sql.DB in the user package?
	}
}

func main() {

	dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s?charset=utf8",
		cfg.DbUser, cfg.DbPass, cfg.DbProtocol, cfg.DbAddress, cfg.DbPort, cfg.DbName)

	db, err := sql.Open("mysql", dsn)
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}

	router := httprouter.New()
	router.GET("/api/user/:id", getUserById(db))
	router.NotFound = &DefaultHandler{}
	log.Fatal(http.ListenAndServe(":8080", router))
}

How should I this? What is a good preferred way, or kind of a best practice?

答案1

得分: 3

超级简单?一个全局的var db *sql.DB对象。*sql.DB是线程安全的,因此可以并发访问。

或者,您可以在一个包装了*sql.DB的类型上定义您的查询方法。我认为func (u *User) FindByID(id string) (*User, error)并没有太多意义 - 您接受一个User指针,但返回一个新的User指针?

作为一个简化的例子,您可以将您的代码更改为以下形式:

type DB struct {
    *sql.DB
}

func NewDB(host, port string) (*DB, error) {
    db, err := sql.Open(...)
    if err != nil {
        return nil, err
    }

    return &DB{db}, nil 
}

func (db *DB) UserByID(id string) (*User, error) {
    res, err := db.Query(...)
    // etc.
}

func (db *DB) UsersList(limit int) ([]*User, error) {
    res, err := db.Query(...)
    // etc.
}

为了从处理程序中调用这些函数,您可以选择:

  • 使用闭包(就像您现在正在做的)
  • 定义一个包含您的DB类型或普通的*sql.DB作为字段的“环境”或“服务”结构,并将您的处理程序定义为该结构的方法。这也可以是全局的(注意任何成员都必须是线程安全的)。
  • 定义一个自定义的处理程序类型(我的方法),在其中调用router.GET("/user/:id", GetUserByID(env))而不是使用闭包。

一些额外的阅读材料:

  1. http://www.alexedwards.net/blog/organising-database-access(涵盖多种方法的最全面的文章之一)
  2. https://robots.thoughtbot.com/interface-with-your-database-in-go
  3. https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091
  4. http://elithrar.github.io/article/http-handler-error-handling-revisited/#a-little-different
英文:

Super simple? A global var db *sql.DB object. *sql.DB is thread-safe and therefore can be accessed concurrently.

Alternatively, you can define your query methods on a type that wraps *sql.DB. It's my opinion that func (u *User) FindByID(id string) (*User, error) doesn't make a whole lot of sense - you accept a User pointer but return a new pointer to a User?

As a simplified example, you could change your code to resemble the below:

type DB struct {
    *sql.DB
}

func NewDB(host, port string) (*DB, error) {
    db, err := sql.Open(...)
    if err != nil {
        return nil, err
    }

    return &DB{db}, nil 
}

func (db *DB) UserByID(id string) (*User, error) {
    res, err := db.Query(...)
    // etc.
}

func (db *DB) UsersList(limit int) ([]*User, error) {
    res, err := db.Query(...)
    // etc.
}

In order to call these functions from your handlers you can either:

  • Use closures (as you are doing now)
  • Define an "environment" or "services" struct that contains your DB type or just vanilla *sql.DB as a field and create your handlers as methods on this. This could also be a global (noting that any members MUST be thread safe).
  • Define a custom handler type (my approach) where you call router.GET("/user/:id", GetUserByID(env) instead of using closures.

Some additional reading:

  1. http://www.alexedwards.net/blog/organising-database-access (covers multiple approaches - one of the most comprehensive articles)
  2. https://robots.thoughtbot.com/interface-with-your-database-in-go
  3. https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091
  4. http://elithrar.github.io/article/http-handler-error-handling-revisited/#a-little-different

huangapple
  • 本文由 发表于 2015年9月4日 09:39:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/32388837.html
匿名

发表评论

匿名网友

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

确定