I'm beginner in go and now want to create a big project my question is where should create connection and where close connection in http requests now i declare db in main function and use in all requests and don't close connection:
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))
}
this code is ok?
Your code is perhaps a test/POC code. In a production project, you could go with a MVC or any other kind of architecture as per your needs. It would be hard to pinpoint the exact structure of your project. But at the very least, you would want to create a db package which declares an interface for all DB related interactions. e.g
The above basically represents a single RDBMS table for this example. There could be
n
such files forn
DB tables. Now callNewUserDBRepo
from the main.go and pass this instance to all services that need this DB.