2023-01-25 19:42:18 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2023-01-28 13:29:39 +00:00
|
|
|
"time"
|
2023-02-04 17:14:23 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2023-01-25 19:42:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type TelegramConfig struct {
|
|
|
|
ChannelID int64 `json:"channel_id"`
|
|
|
|
Token string `json:"token"`
|
|
|
|
}
|
|
|
|
|
2023-02-04 17:14:23 +00:00
|
|
|
type LogConfig struct {
|
|
|
|
Level logrus.Level
|
|
|
|
}
|
|
|
|
|
|
|
|
type jsonLogConfig struct {
|
|
|
|
Level string `json:"level"`
|
|
|
|
}
|
|
|
|
|
2023-01-25 19:42:18 +00:00
|
|
|
type Config struct {
|
2023-01-28 13:29:39 +00:00
|
|
|
Telegram *TelegramConfig
|
|
|
|
PollingFrequency time.Duration
|
2023-02-04 17:14:23 +00:00
|
|
|
Log *LogConfig
|
2023-01-28 13:29:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type jsonConfig struct {
|
|
|
|
Telegram *TelegramConfig `json:"telegram"`
|
|
|
|
PollingFrequency int64 `json:"polling_frequency"`
|
2023-02-04 17:14:23 +00:00
|
|
|
Log *jsonLogConfig `json:"log"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseLevel(lvlStr string) logrus.Level {
|
|
|
|
for _, lvl := range logrus.AllLevels {
|
|
|
|
if lvl.String() == lvlStr {
|
|
|
|
return lvl
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return logrus.InfoLevel
|
2023-01-25 19:42:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
2023-01-28 13:29:39 +00:00
|
|
|
var jsonConf jsonConfig
|
|
|
|
if err := json.Unmarshal(content, &jsonConf); err != nil {
|
2023-01-25 19:42:18 +00:00
|
|
|
return nil, fmt.Errorf("failed to parse config file: %w", err)
|
|
|
|
}
|
2023-01-28 13:29:39 +00:00
|
|
|
return &Config{
|
|
|
|
Telegram: jsonConf.Telegram,
|
|
|
|
PollingFrequency: time.Duration(jsonConf.PollingFrequency) * time.Second,
|
2023-02-04 17:14:23 +00:00
|
|
|
Log: &LogConfig{
|
|
|
|
Level: parseLevel(jsonConf.Log.Level),
|
|
|
|
},
|
2023-01-28 13:29:39 +00:00
|
|
|
}, nil
|
2023-01-25 19:42:18 +00:00
|
|
|
}
|