package config import ( "encoding/json" "fmt" "os" "time" "github.com/sirupsen/logrus" ) type ExportMode int64 const ( ExportNative = iota ExportUnix ) func exportModeFromStr(val string) ExportMode { switch val { case "native": return ExportNative case "unix": return ExportUnix default: return ExportNative } } type TelegramConfig struct { ChannelID int64 `json:"channel_id"` Token string `json:"token"` } type LogConfig struct { Level logrus.Level } type jsonLogConfig struct { Level string `json:"level"` } type ExportConfig struct { Mode ExportMode UnixSock string } type jsonExportConfig struct { Mode string `json:"mode"` UnixSock string `json:"sock_path"` } type Config struct { Telegram *TelegramConfig PollingFrequency time.Duration Hostname string Log LogConfig Export ExportConfig } type jsonConfig struct { Telegram *TelegramConfig `json:"telegram"` PollingFrequency int64 `json:"polling_frequency"` Hostname string `json:"hostname"` Log jsonLogConfig `json:"log"` Export jsonExportConfig `json:"export"` } func parseLevel(lvlStr string) logrus.Level { for _, lvl := range logrus.AllLevels { if lvl.String() == lvlStr { return lvl } } return logrus.InfoLevel } func New(filepath string) (*Config, error) { content, err := os.ReadFile(filepath) if err != nil { return nil, fmt.Errorf("failed to read config file %q: %w", filepath, err) } var jsonConf jsonConfig if err := json.Unmarshal(content, &jsonConf); err != nil { return nil, fmt.Errorf("failed to parse config file: %w", err) } return &Config{ Telegram: jsonConf.Telegram, PollingFrequency: time.Duration(jsonConf.PollingFrequency) * time.Second, Hostname: jsonConf.Hostname, Log: LogConfig{ Level: parseLevel(jsonConf.Log.Level), }, Export: ExportConfig{ UnixSock: jsonConf.Export.UnixSock, Mode: exportModeFromStr(jsonConf.Export.Mode), }, }, nil }