31 lines
484 B
Go
31 lines
484 B
Go
|
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
|
||
|
}
|