db.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package db
  2. import (
  3. "database/sql"
  4. "time"
  5. )
  6. type Env interface {
  7. AppPort() string
  8. DBHost() string
  9. DBPort() string
  10. DBName() string
  11. DBUser() string
  12. DBPassword() string
  13. DBMaxOpenConns() int
  14. DBMaxIdleConns() int
  15. DBMaxConnLifetime() int
  16. DBMaxIdleConnLifetime() int
  17. }
  18. func Init(env Env) (*sql.DB, error) {
  19. dataSource := "user=" + env.DBUser() +
  20. " password=" + env.DBPassword() +
  21. " dbname=" + env.DBName() +
  22. " host=" + env.DBHost() +
  23. " port=" + env.DBPort() +
  24. " sslmode=disable"
  25. db, err := sql.Open("postgres", dataSource)
  26. if err != nil {
  27. return nil, err
  28. }
  29. if env.DBMaxOpenConns() > 0 {
  30. db.SetMaxOpenConns(env.DBMaxOpenConns())
  31. }
  32. if env.DBMaxIdleConns() > 0 {
  33. db.SetMaxIdleConns(env.DBMaxIdleConns())
  34. }
  35. if env.DBMaxConnLifetime() > 0 {
  36. db.SetConnMaxLifetime(time.Second * time.Duration(env.DBMaxConnLifetime()))
  37. }
  38. if env.DBMaxIdleConnLifetime() > 0 {
  39. db.SetConnMaxIdleTime(time.Second * time.Duration(env.DBMaxIdleConnLifetime()))
  40. }
  41. if err = db.Ping(); err != nil {
  42. return nil, err
  43. }
  44. return db, nil
  45. }