go - 如何使用数据库连接实例化模型
问题描述
约束:
- “main.go”中没有所有内容,但每个请求的模型和处理程序文件 register_post.go (handler) user.go (models)
- 不使用全局变量
- 使用依赖注入方便测试
到目前为止,这是我的代码。如果您只使用一种模型,它就可以工作。但是如何扩展它以允许另一个处理程序文件和另一个模型?
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
}
解决方案
推荐阅读
- kubernetes - VSCode Kubernetes 扩展:无法解析配置文件 .aws/config
- node.js - 防止 socket.io 客户端尝试连接
- nginx - 添加位置块后,Nginx Alias 路由不起作用
- javascript - 创建、填充和附加 div
- html - 根据当前路线有条件地渲染手风琴侧面导航(Angular/TS)
- elasticsearch - Linux mint Elasticsearch 启动命令不起作用
- mongodb - 有没有办法将 mongodb 文档与 mongodb 查询过滤器进行比较以查看它们是否匹配
- flutter - 如何在构建函数中同步运行映射函数到颤动中的无状态小部件?
- javascript - 错误:无法使用 Express 和车把获取
- angular - 如何为可观察管道创建两个分支。我不是在谈论 iif