package config
This commit is contained in:
58
internal/config/config.go
Normal file
58
internal/config/config.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig `yaml:"server"`
|
||||
Auth AuthConfig `yaml:"auth"`
|
||||
TLS TLSConfig `yaml:"tls"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
BindAddress string `yaml:"bind_address"`
|
||||
ReadTimeout time.Duration `yaml:"read_timeout"`
|
||||
WriteTimeout time.Duration `yaml:"write_timeout"`
|
||||
}
|
||||
|
||||
type AuthConfig struct {
|
||||
Mode string `yaml:"mode"`
|
||||
Token string `yaml:"token,omitempty"`
|
||||
}
|
||||
|
||||
type TLSConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
CertFile string `yaml:"cert_file"`
|
||||
KeyFile string `yaml:"key_file"`
|
||||
}
|
||||
|
||||
type ConfigLoader interface {
|
||||
LoadConfig() (*Config, error)
|
||||
}
|
||||
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
BindAddress: ":8080",
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
},
|
||||
Auth: AuthConfig{
|
||||
Mode: "none",
|
||||
},
|
||||
TLS: TLSConfig{
|
||||
Enabled: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) applyDefaults() *Config {
|
||||
if c.Server.BindAddress == "" {
|
||||
c.Server.BindAddress = ":8080"
|
||||
}
|
||||
if c.Auth.Mode == "" {
|
||||
c.Auth.Mode = "none"
|
||||
}
|
||||
return &c
|
||||
}
|
||||
29
internal/config/yamlloader.go
Normal file
29
internal/config/yamlloader.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type YamlConfigLoader struct {
|
||||
FilePath string
|
||||
}
|
||||
|
||||
func (l *YamlConfigLoader) LoadConfig() (*Config, error) {
|
||||
data, err := os.ReadFile(l.FilePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return DefaultConfig(), nil
|
||||
}
|
||||
return nil, fmt.Errorf("reading config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parsing config file: %w", err)
|
||||
}
|
||||
|
||||
return cfg.applyDefaults(), nil
|
||||
}
|
||||
Reference in New Issue
Block a user