62 рядки
1.4 KiB
Go
62 рядки
1.4 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"strconv"
|
|
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
type Config struct {
|
|
TelegramBotToken string
|
|
BotOwnerID int64
|
|
DatabaseURL string
|
|
AutoMigrate bool
|
|
}
|
|
|
|
func Load() (Config, error) {
|
|
if err := godotenv.Load(); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
|
return Config{}, fmt.Errorf("load .env: %w", err)
|
|
}
|
|
|
|
cfg := Config{
|
|
TelegramBotToken: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
|
DatabaseURL: os.Getenv("DATABASE_URL"),
|
|
AutoMigrate: true,
|
|
}
|
|
if value := os.Getenv("BOT_OWNER_ID"); value != "" {
|
|
ownerID, err := strconv.ParseInt(value, 10, 64)
|
|
if err != nil || ownerID <= 0 {
|
|
return Config{}, errors.New("BOT_OWNER_ID must be a positive Telegram user ID")
|
|
}
|
|
cfg.BotOwnerID = ownerID
|
|
}
|
|
if value := os.Getenv("AUTO_MIGRATE"); value != "" {
|
|
autoMigrate, err := strconv.ParseBool(value)
|
|
if err != nil {
|
|
return Config{}, fmt.Errorf("AUTO_MIGRATE must be true or false: %w", err)
|
|
}
|
|
cfg.AutoMigrate = autoMigrate
|
|
}
|
|
if err := cfg.validate(); err != nil {
|
|
return Config{}, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func (c Config) validate() error {
|
|
if c.TelegramBotToken == "" {
|
|
return errors.New("TELEGRAM_BOT_TOKEN is required")
|
|
}
|
|
if c.DatabaseURL == "" {
|
|
return errors.New("DATABASE_URL is required")
|
|
}
|
|
if c.BotOwnerID <= 0 {
|
|
return errors.New("BOT_OWNER_ID is required")
|
|
}
|
|
return nil
|
|
}
|