2025-05-24 09:16:47 +06:00

68 lines
1.5 KiB
Go

package config
import (
"log"
"log/slog"
"os"
"strings"
"github.com/joho/godotenv"
)
// Config holds our application's configuration.
type Config struct {
TelegramBotAPIKey string
DBPath string
LogLevel slog.Level
}
// LoadEnv loads environment variables from a .env file (if available).
func LoadEnv() {
if err := godotenv.Load(); err != nil {
log.Println("Warning: .env file not found. Using system environment variables.")
}
}
// GetConfig loads and validates configuration from the environment.
func GetConfig() Config {
// Load .env file first.
LoadEnv()
// Create a config struct.
cfg := Config{}
// Telegram bot's API key must not be empty.
telegramBotAPIKey := os.Getenv("TELEGRAM_BOT_API_KEY")
if telegramBotAPIKey == "" {
panic("TELEGRAM_BOT_API_KEY is required!")
}
cfg.TelegramBotAPIKey = telegramBotAPIKey
// Read DATABASE_FILE and default to badger.db
dbPath := os.Getenv("DATABASE_FILE")
if dbPath == "" {
dbPath = "badger.db"
}
cfg.DBPath = dbPath
// Read LOG_LEVEL and default to info if not set
logLevel := os.Getenv("LOG_LEVEL")
if logLevel == "" {
logLevel = "info"
}
switch strings.ToLower(logLevel) {
case "debug":
cfg.LogLevel = slog.LevelDebug
case "info":
cfg.LogLevel = slog.LevelInfo
case "warn":
cfg.LogLevel = slog.LevelWarn
case "error":
cfg.LogLevel = slog.LevelError
default:
panic("invalid log level! value must be in debug, info, warn, or error!")
}
return cfg
}