This commit is contained in:
77
internal/config/config.go
Normal file
77
internal/config/config.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServerName string `yaml:"server_name"`
|
||||
DiscordWebhookURL string `yaml:"discord_webhook_url"`
|
||||
NotifyRoleID string `yaml:"notify_role_id"`
|
||||
RequestTimeout time.Duration `yaml:"request_timeout"`
|
||||
Backup Backup `yaml:"backup"`
|
||||
}
|
||||
|
||||
type Backup struct {
|
||||
Interval time.Duration `yaml:"interval"`
|
||||
SourceFile string `yaml:"source_file"`
|
||||
OutputDir string `yaml:"output_dir"`
|
||||
FilePrefix string `yaml:"file_prefix"`
|
||||
}
|
||||
|
||||
func Load(path string) (Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
applyDefaults(&cfg)
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func applyDefaults(cfg *Config) {
|
||||
if cfg.RequestTimeout == 0 {
|
||||
cfg.RequestTimeout = 10 * time.Second
|
||||
}
|
||||
if cfg.Backup.Interval == 0 {
|
||||
cfg.Backup.Interval = 24 * time.Hour
|
||||
}
|
||||
if cfg.Backup.FilePrefix == "" {
|
||||
cfg.Backup.FilePrefix = "db"
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg Config) Validate() error {
|
||||
if cfg.ServerName == "" {
|
||||
return fmt.Errorf("server_name is required")
|
||||
}
|
||||
if cfg.DiscordWebhookURL == "" {
|
||||
return fmt.Errorf("discord_webhook_url is required")
|
||||
}
|
||||
if cfg.Backup.Interval <= 0 {
|
||||
return fmt.Errorf("backup.interval must be > 0")
|
||||
}
|
||||
if cfg.Backup.SourceFile == "" {
|
||||
return fmt.Errorf("backup.source_file is required")
|
||||
}
|
||||
if cfg.Backup.OutputDir == "" {
|
||||
return fmt.Errorf("backup.output_dir is required")
|
||||
}
|
||||
if cfg.Backup.FilePrefix == "" {
|
||||
return fmt.Errorf("backup.file_prefix is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user