-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
67 lines (55 loc) · 1.15 KB
/
config.go
File metadata and controls
67 lines (55 loc) · 1.15 KB
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
package main
import (
"fmt"
"log"
"os"
"strconv"
"github.com/joho/godotenv"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type AppConfig struct {
DatabaseConfig
}
type DatabaseConfig struct {
Host string
Port int
User string
Password string
Name string
}
func DatabaseConnection() *gorm.DB {
dsn := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
appConfig.DatabaseConfig.Host,
appConfig.DatabaseConfig.Port,
appConfig.DatabaseConfig.User,
appConfig.DatabaseConfig.Password,
appConfig.DatabaseConfig.Name,
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
return db
}
func ENV(key string) string {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
return os.Getenv(key)
}
func SetAppConfig() AppConfig {
dbPort, _ := strconv.Atoi(ENV("DATABASE_PORT"))
appConfig := AppConfig{
DatabaseConfig: DatabaseConfig{
Host: ENV("DATABASE_HOST"),
Port: dbPort,
User: ENV("DATABASE_USER"),
Password: ENV("DATABASE_PASSWORD"),
Name: ENV("DATABASE_NAME"),
},
}
return appConfig
}