Databases
Database management in Go
Opening DB connection
// The openDB() function wraps sql.Open() and returns a sql.DB connection pool
func openDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
// Set the maximum number of concurrently open (idle + in-use) connections. Setting this
// to less than or equal to 0 will mean there is no maximum limit. If the maximum
// number of open connections is reached and all are in-use when a new connection is
// needed, Go will wait until one of the connections is freed and becomes idle. From a
// user perspective, this means their HTTP request will hang until a connection
// is freed.
db.SetMaxOpenConns(100)
// Set the maximum number of idle connections in the pool. Setting this
// to less than or equal to 0 will mean that no idle connections are retained.
db.SetMaxIdleConns(5)
// Create a context with a 5-second timeout deadline.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Use PingContext() to establish a new connection to the database, passing in the // context we created above as a parameter. If the connection couldn't be
// established successfully within the 5 second deadline, then this will return an // error.
err = db.PingContext(ctx)
if err != nil {
return nil, err
}
return db, nil
}Configuring DB pool
Database Migrations
Last updated