diff options
Diffstat (limited to 'backend/database')
| -rw-r--r-- | backend/database/database.go | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/backend/database/database.go b/backend/database/database.go new file mode 100644 index 0000000..85ebaa2 --- /dev/null +++ b/backend/database/database.go | |||
| @@ -0,0 +1,31 @@ | |||
| 1 | package database | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "database/sql" | ||
| 5 | "fmt" | ||
| 6 | |||
| 7 | _ "github.com/lib/pq" | ||
| 8 | "github.com/pektezol/leastportals/backend/controllers" | ||
| 9 | ) | ||
| 10 | |||
| 11 | var DB *sql.DB | ||
| 12 | |||
| 13 | func ConnectDB() { | ||
| 14 | host := controllers.GetEnvKey("DB_HOST") | ||
| 15 | port := controllers.GetEnvKey("DB_PORT") | ||
| 16 | user := controllers.GetEnvKey("DB_USER") | ||
| 17 | pass := controllers.GetEnvKey("DB_PASS") | ||
| 18 | name := controllers.GetEnvKey("DB_NAME") | ||
| 19 | psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+ | ||
| 20 | "password=%s dbname=%s sslmode=disable", | ||
| 21 | host, port, user, pass, name) | ||
| 22 | db, err := sql.Open("postgres", psqlInfo) | ||
| 23 | if err != nil { | ||
| 24 | panic(err) | ||
| 25 | } | ||
| 26 | if err = db.Ping(); err != nil { | ||
| 27 | panic(err) | ||
| 28 | } | ||
| 29 | DB = db | ||
| 30 | fmt.Println("Successfully connected to database!") | ||
| 31 | } | ||