-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (71 loc) · 1.74 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/ZeeshanTamboli/slack-clone-services/database"
"github.com/ZeeshanTamboli/slack-clone-services/api/handlers"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
const (
dbhost = "DBHOST"
dbport = "DBPORT"
dbuser = "DBUSER"
dbpass = "DBPASS"
dbname = "DBNAME"
)
func init() {
if err := godotenv.Load(); err != nil {
log.Fatal("Env files could not be loaded. Err: ", err)
}
}
func main() {
initDb()
defer database.DBCon.Close() // This will close the db if the server fails to start and exits this main func
handlers.InitializeRoutes()
}
func initDb() {
config := dbConfig()
var err error
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+"password=%s dbname=%s sslmode=disable", config[dbhost], config[dbport], config[dbuser], config[dbpass], config[dbname])
database.DBCon, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
err = database.DBCon.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected")
}
func dbConfig() map[string]string {
conf := make(map[string]string)
host, ok := os.LookupEnv(dbhost)
if !ok {
panic("DBHOST environment variable required but not set")
}
port, ok := os.LookupEnv(dbport)
if !ok {
panic("DBPORT environment variable required but not set")
}
user, ok := os.LookupEnv(dbuser)
if !ok {
panic("DBUSER environment variable required but not set")
}
password, ok := os.LookupEnv(dbpass)
if !ok {
panic("DBPASS environment variable required but not set")
}
name, ok := os.LookupEnv(dbname)
if !ok {
panic("DBNAME environment variable required but not set")
}
conf[dbhost] = host
conf[dbport] = port
conf[dbuser] = user
conf[dbpass] = password
conf[dbname] = name
return conf
}