Files
mtusi2026lab2/internal/config/config.go
T
2026-10-01 12:59:06 +03:00

94 lines
2.1 KiB
Go

package config
import (
"fmt"
"log/slog"
"net"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/spf13/viper"
"mtusi-messenger/internal/logger"
)
const envPrefix = "APP"
type Config struct {
Host string `mapstructure:"host" validate:"required,hostname|ip"`
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
LogLevel string `mapstructure:"log_level" validate:"required,oneof=debug info warn error"`
LogFormat string `mapstructure:"log_format" validate:"required,oneof=json console"`
}
var defaults = map[string]any{
"host": "0.0.0.0",
"port": 8080,
"read_header_timeout": "10s",
"shutdown_timeout": "10s",
"log_level": "info",
"log_format": "json",
}
func Load() (Config, error) {
v := viper.New()
v.SetEnvPrefix(envPrefix)
v.AllowEmptyEnv(true)
v.AutomaticEnv()
for key, value := range defaults {
v.SetDefault(key, value)
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return Config{}, fmt.Errorf("unmarshal config: %w", err)
}
if err := validate.Struct(cfg); err != nil {
return Config{}, fmt.Errorf("validate config: %w", err)
}
return cfg, nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}
func (c Config) SlogLevel() slog.Level {
level, _ := logger.ParseLevel(c.LogLevel)
return level
}
func (c Config) LoggerFormat() logger.Format {
format, _ := logger.ParseFormat(c.LogFormat)
return format
}
var validate = newValidator()
func newValidator() *validator.Validate {
v := validator.New(validator.WithRequiredStructEnabled())
v.RegisterTagNameFunc(envName)
return v
}
func envName(field reflect.StructField) string {
key := field.Tag.Get("mapstructure")
if key == "" {
return field.Name
}
return envPrefix + "_" + strings.ToUpper(key)
}