我是 go 初学者,现在想创建一个大项目 我的问题是应该在哪里创建连接以及在 http 请求中关闭连接 现在我在主函数中声明数据库并在所有请求中使用并且不关闭连接:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/middleware/recover"
_ "github.com/go-sql-driver/mysql"
)
var db *gorm.DB
func main() {
port := "8080"
app := iris.New()
app.Configure()
app.Logger().SetLevel("debug")
app.Use(recover.New())
db1, err := gorm.Open("mysql", "root:@/database?charset=utf8&parseTime=True&loc=Local")
//db1, err := gorm.Open("mysql", "payro:AEkCpNhd@/payro_db?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Println(err.Error())
panic(err)
}
db=db1
app.Get("/", func(i context.Context) {
db.Exec("update tbl1 set col1=''")
i.Next()
})
app.Get("/test", func(i context.Context) {
db.Exec("update tbl2 set col2=''")
i.Next()
})
_ = app.Run(iris.Addr(":"+port), iris.WithConfiguration(iris.Configuration{
//DisableBodyConsumptionOnUnmarshal:true,
}), iris.WithoutServerError(iris.ErrServerClosed))
}
这段代码可以吗?
最佳答案
您的代码可能是测试/POC 代码。 在生产项目中,您可以根据需要使用 MVC 或任何其他类型的架构。 很难确定项目的确切结构。 但至少,您需要创建一个 db 包,它为所有与数据库相关的交互声明一个接口(interface)。 例如
type UserDBRepo interface{
AddUser(context.Context, *User)
GetUser(context.Context, uint64)
}
type userDBRepo struct{ //implements UserDBRepo
*sql.DB // or whatever type gorm.Open returns
}
func NewUserDBRepo(db *sql.DB) DBRepo{
return &dbRepo{DB: db}
}
上面基本上代表了这个例子的单个 RDBMS 表。
n
数据库表可能有 n
个这样的文件。
现在从 main.go 调用 NewUserDBRepo
并将此实例传递给需要此 DB 的所有服务。
关于mysql - 如何打开和关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54213310/