diff --git a/cmd/main.go b/cmd/main.go index 64f9fa3..1f2430c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -3,6 +3,7 @@ package cmd import ( "flag" "fmt" + "log/slog" "os" "git.a71.su/Andrew71/pye/cmd/serve" @@ -10,14 +11,10 @@ import ( "git.a71.su/Andrew71/pye/config" ) -func Run() { - // configFlag := flag.String("config", "", "override config file") - // flag.Parse() - // if *configFlag != "" { - // config.Load() - // } +func Run() { serveCmd := flag.NewFlagSet("serve", flag.ExitOnError) + serveConfig := serveCmd.String("config", "", "override config file") servePort := serveCmd.Int("port", 0, "override port") serveDb := serveCmd.String("db", "", "override sqlite database") @@ -31,6 +28,12 @@ func Run() { switch os.Args[1] { case "serve": 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 { config.Cfg.Port = *servePort } diff --git a/config.json b/config.json new file mode 100644 index 0000000..152ae68 --- /dev/null +++ b/config.json @@ -0,0 +1,5 @@ +{ + "port": 7102, + "key-file": "private.key", + "sqlite-file": "data.db" +} \ No newline at end of file diff --git a/config/config.go b/config/config.go index d05fa2a..565c12a 100644 --- a/config/config.go +++ b/config/config.go @@ -1,5 +1,11 @@ package config +import ( + "encoding/json" + "log/slog" + "os" +) + type Config struct { Port int `json:"port"` KeyFile string `json:"key-file"` @@ -7,14 +13,39 @@ type Config struct { } var DefaultConfig = Config{ - Port: 7102, - KeyFile: "private.key", + Port: 7102, + KeyFile: "private.key", SQLiteFile: "data.db", } -var Cfg = MustLoadConfig() +var ( + DefaultLocation = "config.json" + Cfg Config +) -// TODO: Implement -func MustLoadConfig() Config { - return DefaultConfig -} \ No newline at end of file +func LoadConfig(filename string) error { + data, err := os.ReadFile(filename) + 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() +}