package common import ( "database/sql" "fmt" "os" _ "github.com/lib/pq" "github.com/pelletier/go-toml/v2" ) 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() (*sql.DB, error) { return sql.Open("postgres", p.generateDsn()) } // 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 LoadConfig(path string) (*Config, error) { b, err := os.ReadFile(path) var cfg Config if err != nil { if !os.IsNotExist(err) { return nil, err } cfg.SetDefaultValues() b, err := toml.Marshal(cfg) if err != nil { return nil, err } return nil, os.WriteFile(path, b, 0600) } return &cfg, toml.Unmarshal(b, &cfg) }