首页 > 解决方案 > 如何使用数据库连接实例化模型

问题描述

约束:

  1. “main.go”中没有所有内容,但每个请求的模型和处理程序文件 register_post.go (handler) user.go (models)
  2. 不使用全局变量
  3. 使用依赖注入方便测试

到目前为止,这是我的代码。如果您只使用一种模型,它就可以工作。但是如何扩展它以允许另一个处理程序文件和另一个模型?

main.go

// Initalise Env with a models.BookModel instance (which in turn wraps
// the connection pool).
env := &handler.Env{
    Books: models.BookModel{DB: db},
}
// route call
v1.GET("/books", env.BooksIndex)

books_get.go 处理程序

// // Initalise Env with a models.BookModel instance (which in turn wraps
// // the connection pool)

type Env struct {
    // Replace the reference to models.BookModel with an interface
    // describing its methods.
    Books interface {
        All() ([]models.Book, error)
    }
}



func (env *Env) BooksIndex(c echo.Context) error {


// Execute the SQL query by calling the All() method.
bks, err := env.Books.All()

if err != nil {
    fmt.Println(err)
    return err
}
return c.JSON(http.StatusOK, bks)

}

book.go 模型

func (m BookModel) All() ([]Book, error) {
    // some body
}

标签: godependency-injection

解决方案


推荐阅读