package app import ( "database/sql" "fmt" "os" ) const ( dbhost = "dbhost" dbport = "dbport" dbuser = "dbuser" dbpass = "dbpass" dbname = "dbname" ) const ( SqlGetUser = ` SELECT user_id, title, created_on, uuid FROM users WHERE title=$1; ` SqlPostUser = ` INSERT INTO users (title, created_on,uuid) VALUES ($1, $2, $3) RETURNING user_id` ) var Db *sql.DB func InitDb() { config := dbConfig() var err error psqlInfo := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable", config[dbuser], config[dbpass], config[dbhost], config[dbport], config[dbname]) fmt.Println(psqlInfo) Db, err = sql.Open("postgres", psqlInfo) if err != nil { panic(err) } err = Db.Ping() if err != nil { panic(err) } fmt.Println("Successfully connected!") } func CloseDB() { Db.Close() } 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 }