lab2
This commit is contained in:
+162
-16
@@ -1,9 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -15,35 +19,134 @@ import (
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
const envPrefix = "APP"
|
||||
const (
|
||||
configEnvKey = "APP_CONFIG"
|
||||
envKey = "APP_ENV"
|
||||
configName = "config"
|
||||
defaultEnv = "dev"
|
||||
configDir = "./config/"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
|
||||
Server Server `mapstructure:"server"`
|
||||
Log Log `mapstructure:"log"`
|
||||
Postgres Postgres `mapstructure:"postgres"`
|
||||
Redis Redis `mapstructure:"redis"`
|
||||
Cache Cache `mapstructure:"cache"`
|
||||
Session Session `mapstructure:"session"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Redis struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
|
||||
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
|
||||
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
||||
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
||||
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Server 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"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
|
||||
Format string `mapstructure:"format" validate:"required,oneof=json console"`
|
||||
}
|
||||
|
||||
type Postgres struct {
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Database string `mapstructure:"database" validate:"omitempty,min=1"`
|
||||
User string `mapstructure:"user" validate:"omitempty,min=1"`
|
||||
Password string `mapstructure:"password"`
|
||||
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
|
||||
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
|
||||
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
|
||||
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
|
||||
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
|
||||
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
func (p Postgres) DSN() string {
|
||||
u := &url.URL{
|
||||
Scheme: "postgres",
|
||||
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
|
||||
Path: "/" + p.Database,
|
||||
}
|
||||
|
||||
if p.Password == "" {
|
||||
u.User = url.User(p.User)
|
||||
} else {
|
||||
u.User = url.UserPassword(p.User, p.Password)
|
||||
}
|
||||
|
||||
query := url.Values{}
|
||||
query.Set("sslmode", p.SSLMode)
|
||||
u.RawQuery = query.Encode()
|
||||
|
||||
return u.String()
|
||||
}
|
||||
|
||||
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",
|
||||
"env": "dev",
|
||||
"server.host": "0.0.0.0",
|
||||
"server.port": 8080,
|
||||
"server.read_header_timeout": "10s",
|
||||
"server.shutdown_timeout": "10s",
|
||||
"log.level": "info",
|
||||
"log.format": "json",
|
||||
"session.ttl_seconds": 3600,
|
||||
"redis.enabled": false,
|
||||
"redis.host": "localhost",
|
||||
"redis.port": 6379,
|
||||
"redis.db": 0,
|
||||
"redis.max_retries": -1,
|
||||
"redis.dial_timeout": "300ms",
|
||||
"redis.read_timeout": "200ms",
|
||||
"redis.write_timeout": "200ms",
|
||||
"redis.pool_size": 10,
|
||||
"cache.enabled": false,
|
||||
"cache.chat_list_ttl": "5m",
|
||||
"cache.lock_ttl": "10s",
|
||||
"cache.lock_wait_timeout": "2s",
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
v := viper.New()
|
||||
|
||||
v.SetEnvPrefix(envPrefix)
|
||||
if err := configureSource(v); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
v.AllowEmptyEnv(true)
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
for key := range defaults {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
@@ -55,21 +158,64 @@ func Load() (Config, error) {
|
||||
return Config{}, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
if err := cfg.validateDependencies(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) validateDependencies() error {
|
||||
if c.Cache.Enabled && !c.Redis.Enabled {
|
||||
return errors.New("validate config: cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func configureSource(v *viper.Viper) error {
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
if path := os.Getenv(configEnvKey); path != "" {
|
||||
v.SetConfigFile(path)
|
||||
} else {
|
||||
env := os.Getenv(envKey)
|
||||
if env == "" {
|
||||
env = defaultEnv
|
||||
}
|
||||
|
||||
v.SetConfigName(configName)
|
||||
v.AddConfigPath(filepath.Join(configDir, env))
|
||||
}
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
var notFound viper.ConfigFileNotFoundError
|
||||
if errors.As(err, ¬Found) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("read config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
|
||||
}
|
||||
|
||||
func (c Config) SlogLevel() slog.Level {
|
||||
level, _ := logger.ParseLevel(c.LogLevel)
|
||||
level, _ := logger.ParseLevel(c.Log.Level)
|
||||
|
||||
return level
|
||||
}
|
||||
|
||||
func (c Config) LoggerFormat() logger.Format {
|
||||
format, _ := logger.ParseFormat(c.LogFormat)
|
||||
format, _ := logger.ParseFormat(c.Log.Format)
|
||||
|
||||
return format
|
||||
}
|
||||
@@ -89,5 +235,5 @@ func envName(field reflect.StructField) string {
|
||||
return field.Name
|
||||
}
|
||||
|
||||
return envPrefix + "_" + strings.ToUpper(key)
|
||||
return strings.ToUpper(key)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user