aboutsummaryrefslogtreecommitdiff
path: root/config.go
blob: 725074c8512bfa988f1fba82d0709b61d77acad7 (plain)
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
package main

import (
	"fmt"
	"os"

	"github.com/pelletier/go-toml/v2"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Config struct {
	Debug    bool            `toml:"debug"`
	Author   string          `toml:"author"`
	Database *PostgresConfig `toml:"database"`
}

type PostgresConfig struct {
	Host     string `toml:"host"`
	User     string `toml:"user"`
	Password string `toml:"password"`
	DBName   string `toml:"db_name"`
	Port     int    `toml:"port"`
}

func (p *PostgresConfig) SetDefaultValues() {
	p.Host = "localhost"
	p.User = ""
	p.Password = ""
	p.DBName = ""
	p.Port = 5432
}

func (p *PostgresConfig) Connect() (*gorm.DB, error) {
	db, err := gorm.Open(postgres.Open(p.generateDsn()), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	return db, nil
}

// generateDsn for the connection to postgres using the given config.SQLCredentials
func (p *PostgresConfig) generateDsn() string {
	return fmt.Sprintf(
		"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Europe/Paris",
		p.Host, p.User, p.Password, p.DBName, p.Port,
	)
}

func (c *Config) SetDefaultValues() {
	c.Debug = false
	c.Author = "anhgelus"
	c.Database = &PostgresConfig{}
	c.Database.SetDefaultValues()
}

func getConfig(path string) (*Config, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var cfg Config
	return &cfg, toml.Unmarshal(b, &cfg)
}