first commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
// DB global var (may be nil if connection fails)
|
||||
var DB *sql.DB
|
||||
|
||||
// Use the credentials you provided
|
||||
const (
|
||||
host = "202.46.28.160"
|
||||
port = 45432
|
||||
user = "5803024022"
|
||||
password = "PW5803024022"
|
||||
dbname = "tgs03_5803024022"
|
||||
)
|
||||
|
||||
// InitDB attempts to open a connection pool to Postgres.
|
||||
// It returns error if ping fails.
|
||||
func InitDB() (*sql.DB, error) {
|
||||
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
|
||||
host, port, user, password, dbname)
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// reasonable settings
|
||||
db.SetMaxOpenConns(10)
|
||||
db.SetMaxIdleConns(5)
|
||||
db.SetConnMaxLifetime(time.Minute * 5)
|
||||
|
||||
// Ping with timeout
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- db.Ping()
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
return nil, fmt.Errorf("db ping timeout")
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user