Load config from file

This commit is contained in:
Andrew-71 2024-10-12 22:15:44 +03:00
parent 82aba0c9e9
commit 7fbe06c2ab
3 changed files with 52 additions and 13 deletions

View file

@ -3,6 +3,7 @@ package cmd
import ( import (
"flag" "flag"
"fmt" "fmt"
"log/slog"
"os" "os"
"git.a71.su/Andrew71/pye/cmd/serve" "git.a71.su/Andrew71/pye/cmd/serve"
@ -11,13 +12,9 @@ import (
) )
func Run() { func Run() {
// configFlag := flag.String("config", "", "override config file")
// flag.Parse()
// if *configFlag != "" {
// config.Load()
// }
serveCmd := flag.NewFlagSet("serve", flag.ExitOnError) serveCmd := flag.NewFlagSet("serve", flag.ExitOnError)
serveConfig := serveCmd.String("config", "", "override config file")
servePort := serveCmd.Int("port", 0, "override port") servePort := serveCmd.Int("port", 0, "override port")
serveDb := serveCmd.String("db", "", "override sqlite database") serveDb := serveCmd.String("db", "", "override sqlite database")
@ -31,6 +28,12 @@ func Run() {
switch os.Args[1] { switch os.Args[1] {
case "serve": case "serve":
serveCmd.Parse(os.Args[2:]) serveCmd.Parse(os.Args[2:])
if *serveConfig != "" {
err := config.LoadConfig(*serveConfig)
if err != nil {
slog.Error("error loading custom config", "error", err)
}
}
if *servePort != 0 { if *servePort != 0 {
config.Cfg.Port = *servePort config.Cfg.Port = *servePort
} }

5
config.json Normal file
View file

@ -0,0 +1,5 @@
{
"port": 7102,
"key-file": "private.key",
"sqlite-file": "data.db"
}

View file

@ -1,5 +1,11 @@
package config package config
import (
"encoding/json"
"log/slog"
"os"
)
type Config struct { type Config struct {
Port int `json:"port"` Port int `json:"port"`
KeyFile string `json:"key-file"` KeyFile string `json:"key-file"`
@ -12,9 +18,34 @@ var DefaultConfig = Config{
SQLiteFile: "data.db", SQLiteFile: "data.db",
} }
var Cfg = MustLoadConfig() var (
DefaultLocation = "config.json"
Cfg Config
)
// TODO: Implement func LoadConfig(filename string) error {
func MustLoadConfig() Config { data, err := os.ReadFile(filename)
return DefaultConfig if err != nil {
return err
}
temp_config := DefaultConfig
err = json.Unmarshal(data, &temp_config)
if err != nil {
return err
}
Cfg = temp_config
slog.Info("Loaded config", "file", filename)
return nil
}
func MustLoadConfig() {
err := LoadConfig(DefaultLocation)
if err != nil {
slog.Error("error initially loading config", "error", err)
os.Exit(1)
}
}
func init() {
MustLoadConfig()
} }