Files
nidus/internal/config/config.go
T

73 lines
1.4 KiB
Go

package config
import (
"fmt"
"os"
"strconv"
)
// Config is the top-level server configuration.
type Config struct {
Server ServerConfig
Auth AuthConfig
Storage StorageConfig
Logging LoggingConfig
}
type ServerConfig struct {
Host string
Port int
BaseURL string
}
type AuthConfig struct {
Realm string
}
type StorageConfig struct {
DataDir string
}
type LoggingConfig struct {
Level string
Format string
}
// Load reads and parses environment variables to create the configuration.
func Load() (*Config, error) {
cfg := &Config{}
cfg.applyDefaults()
return cfg, nil
}
func (c *Config) applyDefaults() {
c.Server.Host = getEnv("NIDUS_HOST", "0.0.0.0")
c.Server.Port = getEnvInt("NIDUS_PORT", 8080)
c.Server.BaseURL = getEnv("NIDUS_BASE_URL", "")
if c.Server.BaseURL == "" {
c.Server.BaseURL = fmt.Sprintf("http://%s:%d", c.Server.Host, c.Server.Port)
}
c.Auth.Realm = getEnv("NIDUS_AUTH_REALM", "DAV Server")
c.Storage.DataDir = getEnv("NIDUS_DATA_DIR", "./data")
c.Logging.Level = getEnv("NIDUS_LOG_LEVEL", "info")
c.Logging.Format = getEnv("NIDUS_LOG_FORMAT", "text")
}
func getEnv(key string, defaultValue string) string {
if val := os.Getenv(key); val != "" {
return val
}
return defaultValue
}
func getEnvInt(key string, defaultValue int) int {
if val := os.Getenv(key); val != "" {
if intVal, err := strconv.Atoi(val); err == nil {
return intVal
}
}
return defaultValue
}