feat(config): support cli config path and nested config
Adds -config CLI flag to main.go. Moves ParseLogLevel to internal/config. Adds ServerConfig nested struct to Config and corresponding tests for yaml/env overrides.
This commit is contained in:
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
@@ -13,7 +14,14 @@ import (
|
||||
|
||||
// Config holds the application configuration.
|
||||
type Config struct {
|
||||
LogLevel string `yaml:"log_level"`
|
||||
LogLevel string `yaml:"log_level"`
|
||||
Server ServerConfig `yaml:"server"`
|
||||
}
|
||||
|
||||
// ServerConfig holds server-specific configuration.
|
||||
type ServerConfig struct {
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
}
|
||||
|
||||
// Load reads configuration from a YAML file and overrides it with environment variables.
|
||||
@@ -42,6 +50,22 @@ func Load(configPath string, envPrefix string) (*Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// ParseLogLevel converts a string log level to a slog.Level.
|
||||
func ParseLogLevel(level string) slog.Level {
|
||||
switch strings.ToLower(level) {
|
||||
case "debug":
|
||||
return slog.LevelDebug
|
||||
case "info":
|
||||
return slog.LevelInfo
|
||||
case "warn":
|
||||
return slog.LevelWarn
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
|
||||
// overrideFromEnv uses reflection to traverse the struct and update fields from env vars.
|
||||
func overrideFromEnv(cfg interface{}, prefix string) error {
|
||||
v := reflect.ValueOf(cfg)
|
||||
|
||||
Reference in New Issue
Block a user