From e3480d0fb436ac202bd175fac96cba4a0d980a36 Mon Sep 17 00:00:00 2001 From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> Date: Mon, 24 Oct 2022 00:40:44 +0300 Subject: add database integration --- backend/database/database.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 backend/database/database.go (limited to 'backend/database') 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 @@ +package database + +import ( + "database/sql" + "fmt" + + _ "github.com/lib/pq" + "github.com/pektezol/leastportals/backend/controllers" +) + +var DB *sql.DB + +func ConnectDB() { + host := controllers.GetEnvKey("DB_HOST") + port := controllers.GetEnvKey("DB_PORT") + user := controllers.GetEnvKey("DB_USER") + pass := controllers.GetEnvKey("DB_PASS") + name := controllers.GetEnvKey("DB_NAME") + psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+ + "password=%s dbname=%s sslmode=disable", + host, port, user, pass, name) + db, err := sql.Open("postgres", psqlInfo) + if err != nil { + panic(err) + } + if err = db.Ping(); err != nil { + panic(err) + } + DB = db + fmt.Println("Successfully connected to database!") +} -- cgit v1.2.3