2024-10-12 21:45:00 +03:00
|
|
|
package config
|
|
|
|
|
2024-10-12 22:15:44 +03:00
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"log/slog"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2024-10-13 17:33:59 +03:00
|
|
|
// Config stores app configuration
|
2024-10-12 21:45:00 +03:00
|
|
|
type Config struct {
|
|
|
|
Port int `json:"port"`
|
|
|
|
KeyFile string `json:"key-file"`
|
|
|
|
SQLiteFile string `json:"sqlite-file"`
|
2024-10-13 11:25:00 +03:00
|
|
|
LogToFile bool `json:"log-to-file"`
|
|
|
|
LogFile string `json:"log-file"`
|
2024-10-12 21:45:00 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
var DefaultConfig = Config{
|
2024-10-12 22:15:44 +03:00
|
|
|
Port: 7102,
|
|
|
|
KeyFile: "private.key",
|
2024-10-12 21:45:00 +03:00
|
|
|
SQLiteFile: "data.db",
|
2024-10-13 11:25:00 +03:00
|
|
|
LogToFile: false,
|
|
|
|
LogFile: "pye.log",
|
2024-10-12 21:45:00 +03:00
|
|
|
}
|
|
|
|
|
2024-10-12 22:15:44 +03:00
|
|
|
var (
|
|
|
|
DefaultLocation = "config.json"
|
|
|
|
Cfg Config
|
|
|
|
)
|
|
|
|
|
2024-10-13 17:33:59 +03:00
|
|
|
// Load parses a JSON-formatted configuration file
|
|
|
|
func load(filename string) (Config, error) {
|
2024-10-12 22:15:44 +03:00
|
|
|
data, err := os.ReadFile(filename)
|
|
|
|
if err != nil {
|
2024-10-13 17:33:59 +03:00
|
|
|
return Config{}, err
|
2024-10-12 22:15:44 +03:00
|
|
|
}
|
2024-10-13 17:33:59 +03:00
|
|
|
conf := DefaultConfig
|
|
|
|
err = json.Unmarshal(data, &conf)
|
2024-10-12 22:15:44 +03:00
|
|
|
if err != nil {
|
2024-10-13 17:33:59 +03:00
|
|
|
return Config{}, err
|
2024-10-12 22:15:44 +03:00
|
|
|
}
|
2024-10-13 17:33:59 +03:00
|
|
|
slog.Debug("Loaded config", "file", filename, "config", conf)
|
|
|
|
return conf, nil
|
2024-10-12 22:15:44 +03:00
|
|
|
}
|
|
|
|
|
2024-10-13 17:33:59 +03:00
|
|
|
// MustLoad handles initial configuration loading
|
2024-10-13 17:18:53 +03:00
|
|
|
func MustLoad(filename string) {
|
2024-10-13 17:33:59 +03:00
|
|
|
conf, err := load(filename)
|
2024-10-12 22:15:44 +03:00
|
|
|
if err != nil {
|
|
|
|
slog.Error("error initially loading config", "error", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2024-10-13 17:33:59 +03:00
|
|
|
Cfg = conf
|
|
|
|
}
|