udemy-go-web-2/internal/driver/driver.go

31 lines
484 B
Go
Raw Normal View History

2024-08-04 21:06:13 +00:00
package driver
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
func OpenDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)
err = db.PingContext(ctx)
if err != nil {
fmt.Println(err)
return nil, err
}
return db, nil
}