63 lines
2.1 KiB
Go
63 lines
2.1 KiB
Go
package db
|
|
|
|
import (
|
|
"git.haelnorr.com/h/golib/env"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
type Config struct {
|
|
User string `ezconf:"DB_USER,required,description:Database user for authentication"`
|
|
Password string `ezconf:"DB_PASSWORD,required,description:Database password for authentication"`
|
|
Host string `ezconf:"DB_HOST,required,description:Database host address"`
|
|
Port uint16 `ezconf:"DB_PORT,default:5432,description:Database port"`
|
|
DB string `ezconf:"DB_NAME,required,description:Database to connect to"`
|
|
SSL string `ezconf:"DB_SSL,default:disable,description:SSL Mode"`
|
|
BackupDir string `ezconf:"DB_BACKUP_DIR,default:backups,description:Directory for database backups"`
|
|
BackupRetention int `ezconf:"DB_BACKUP_RETENTION,default:10,description:Number of backups to keep"`
|
|
}
|
|
|
|
func ConfigFromEnv() (any, error) {
|
|
cfg := &Config{
|
|
User: env.String("DB_USER", ""),
|
|
Password: env.String("DB_PASSWORD", ""),
|
|
Host: env.String("DB_HOST", ""),
|
|
Port: env.UInt16("DB_PORT", 5432),
|
|
DB: env.String("DB_NAME", ""),
|
|
SSL: env.String("DB_SSL", "disable"),
|
|
BackupDir: env.String("DB_BACKUP_DIR", "backups"),
|
|
BackupRetention: env.Int("DB_BACKUP_RETENTION", 10),
|
|
}
|
|
|
|
// Validate SSL mode
|
|
validSSLModes := map[string]bool{
|
|
"disable": true,
|
|
"require": true,
|
|
"verify-ca": true,
|
|
"verify-full": true,
|
|
"allow": true,
|
|
"prefer": true,
|
|
}
|
|
if !validSSLModes[cfg.SSL] {
|
|
return nil, errors.Errorf("Invalid DB_SSL value: %s. Must be one of: disable, allow, prefer, require, verify-ca, verify-full", cfg.SSL)
|
|
}
|
|
|
|
// Check required fields
|
|
if cfg.User == "" {
|
|
return nil, errors.New("Envar not set: DB_USER")
|
|
}
|
|
if cfg.Password == "" {
|
|
return nil, errors.New("Envar not set: DB_PASSWORD")
|
|
}
|
|
if cfg.Host == "" {
|
|
return nil, errors.New("Envar not set: DB_HOST")
|
|
}
|
|
if cfg.DB == "" {
|
|
return nil, errors.New("Envar not set: DB_NAME")
|
|
}
|
|
if cfg.BackupRetention < 1 {
|
|
return nil, errors.New("DB_BACKUP_RETENTION must be at least 1")
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|