Skip to content

Instantly share code, notes, and snippets.

@m00zi
Created January 14, 2021 09:46
Show Gist options
  • Save m00zi/ddc213a2c5ce2a5c838b2f5ff6a0eb05 to your computer and use it in GitHub Desktop.
Save m00zi/ddc213a2c5ce2a5c838b2f5ff6a0eb05 to your computer and use it in GitHub Desktop.
Gorm v2 connect to database
// Connect to database
func InitDataDB(dsn string, autoMigrate bool) (db *gorm.DB, err error) {
db, err = gorm.Open("mysql", dsn)
if err != nil {
log.Fatalf("error while open connection to database: %v\n", err)
}
//SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
//If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be
//reduced to match the MaxOpenConns limit.
//If n <= 0, no idle connections are retained.
//The default max idle connections is currently 2. This may change in a future release.
db.DB().SetMaxIdleConns(0)
//SetMaxOpenConns sets the maximum number of open connections to the database.
//If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will
//be reduced to match the new MaxOpenConns limit.
//If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).
db.DB().SetMaxOpenConns(2000)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
db.DB().SetConnMaxLifetime(time.Minute*30)
//SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
// Expired connections may be closed lazily before reuse.
// If d <= 0, connections are not closed due to a connection's idle time.
db.DB().SetConnMaxIdleTime(time.Hour)
db.LogMode(false)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment