89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type Config struct {
|
|
Server ServerConfig `yaml:"server"`
|
|
Database DatabaseConfig `yaml:"database"`
|
|
Log LogConfig `yaml:"log"`
|
|
}
|
|
|
|
type ServerConfig struct {
|
|
Address string `yaml:"address"`
|
|
}
|
|
|
|
type DatabaseConfig struct {
|
|
Address string `yaml:"address"`
|
|
Username string `yaml:"username"`
|
|
Password string `yaml:"password"`
|
|
Database string `yaml:"database"`
|
|
Schema string `yaml:"schema"`
|
|
SSLMode string `yaml:"sslmode"`
|
|
MaxOpenConns int `yaml:"max_open_conns"`
|
|
MaxIdleConns int `yaml:"max_idle_conns"`
|
|
ConnMaxLifetime string `yaml:"conn_max_lifetime"`
|
|
ConnMaxIdleTime string `yaml:"conn_max_idle_time"`
|
|
}
|
|
|
|
type LogConfig struct {
|
|
Level string `yaml:"level"`
|
|
Output string `yaml:"output"`
|
|
FilePath string `yaml:"file_path"`
|
|
}
|
|
|
|
func Load(path string) (*Config, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read config: %w", err)
|
|
}
|
|
|
|
var cfg Config
|
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
|
return nil, fmt.Errorf("parse config: %w", err)
|
|
}
|
|
|
|
applyDefaults(&cfg)
|
|
return &cfg, nil
|
|
}
|
|
|
|
func applyDefaults(cfg *Config) {
|
|
if cfg.Server.Address == "" {
|
|
cfg.Server.Address = ":21056"
|
|
}
|
|
if cfg.Log.Level == "" {
|
|
cfg.Log.Level = "info"
|
|
}
|
|
if cfg.Log.Output == "" {
|
|
cfg.Log.Output = "console"
|
|
}
|
|
if cfg.Log.FilePath == "" {
|
|
cfg.Log.FilePath = "/app/log/app.log"
|
|
}
|
|
if cfg.Database.MaxOpenConns == 0 {
|
|
cfg.Database.MaxOpenConns = 10
|
|
}
|
|
if cfg.Database.MaxIdleConns == 0 {
|
|
cfg.Database.MaxIdleConns = 5
|
|
}
|
|
if cfg.Database.Address == "" {
|
|
cfg.Database.Address = "localhost:5432"
|
|
}
|
|
if cfg.Database.Schema == "" {
|
|
cfg.Database.Schema = "public"
|
|
}
|
|
if cfg.Database.SSLMode == "" {
|
|
cfg.Database.SSLMode = "disable"
|
|
}
|
|
if cfg.Database.ConnMaxLifetime == "" {
|
|
cfg.Database.ConnMaxLifetime = "30m"
|
|
}
|
|
if cfg.Database.ConnMaxIdleTime == "" {
|
|
cfg.Database.ConnMaxIdleTime = "5m"
|
|
}
|
|
}
|