简体   繁体   中英

How to open and close database connection

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. eg

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}
}

The above basically represents a single RDBMS table for this example. There could be n such files for n DB tables. Now call NewUserDBRepo from the main.go and pass this instance to all services that need this DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM