80 lines
1.2 KiB
Go
80 lines
1.2 KiB
Go
|
package common
|
||
|
|
||
|
import (
|
||
|
"os"
|
||
|
"strings"
|
||
|
|
||
|
"github.com/pelletier/go-toml/v2"
|
||
|
"github.com/rs/zerolog"
|
||
|
l "github.com/rs/zerolog/log"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ConfigPath = "./config.toml"
|
||
|
DefaultLogLevel = "info"
|
||
|
DefaultPort = 8080
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
Log log
|
||
|
Http http
|
||
|
}
|
||
|
|
||
|
type http struct {
|
||
|
Port uint16
|
||
|
}
|
||
|
|
||
|
type log struct {
|
||
|
Level string
|
||
|
}
|
||
|
|
||
|
func defaultConfig() Config {
|
||
|
return Config{
|
||
|
Log: log{
|
||
|
Level: DefaultLogLevel,
|
||
|
},
|
||
|
Http: http{
|
||
|
Port: DefaultPort,
|
||
|
},
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func loadConfig(path string) Config {
|
||
|
logger := l.Error().Str("path", path)
|
||
|
config := defaultConfig()
|
||
|
|
||
|
file, err := os.Open(path)
|
||
|
if err != nil {
|
||
|
logger.Err(err).Msg("cannot open file, using default config")
|
||
|
return config
|
||
|
}
|
||
|
|
||
|
dec := toml.NewDecoder(file)
|
||
|
err = dec.Decode(&config)
|
||
|
if err != nil {
|
||
|
logger.Err(err).Msg("cannot parse config, using default")
|
||
|
return config
|
||
|
}
|
||
|
|
||
|
return config
|
||
|
}
|
||
|
|
||
|
func NewConfig() Config {
|
||
|
return loadConfig(ConfigPath)
|
||
|
}
|
||
|
|
||
|
func (c *Config) LogLevel() zerolog.Level {
|
||
|
switch strings.ToLower(c.Log.Level) {
|
||
|
case "error":
|
||
|
return zerolog.ErrorLevel
|
||
|
case "debug":
|
||
|
return zerolog.DebugLevel
|
||
|
case "trace":
|
||
|
return zerolog.TraceLevel
|
||
|
case "warn":
|
||
|
return zerolog.WarnLevel
|
||
|
default:
|
||
|
return zerolog.InfoLevel
|
||
|
}
|
||
|
}
|