From d38a827d8469b314af8ea621b4029fcd1a732664 Mon Sep 17 00:00:00 2001 From: Fabian Vowie Date: Mon, 17 Jan 2022 12:07:38 +0100 Subject: [PATCH] Load settings on program start or create default if none exist --- main.go | 12 ++++++++++-- settings/settings.go | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index aef8790..94a9017 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/geplauder/lithium/pipelines" + "github.com/geplauder/lithium/settings" "github.com/geplauder/lithium/storage" "github.com/gorilla/mux" ) @@ -42,10 +43,17 @@ func RegisterPipelineRoutes(r *mux.Router, pipelines []pipelines.IPipeline, stor } func main() { - storageProvider := storage.GetFileSystemStorageProvider("test") + settings := settings.LoadSettings() + var storageProvider storage.IStorageProvider storageProvider.StoreRaw("abc", "def.test", []byte{0x12, 0x10}) + if settings.FileSystem.Type == 0 { + storageProvider = storage.GetFileSystemStorageProvider(settings.FileSystem.BasePath) + } else { + panic("Invalid file system provided!") + } + pipes := pipelines.LoadPipelines() r := mux.NewRouter() @@ -53,7 +61,7 @@ func main() { RegisterPipelineRoutes(r, pipes, storageProvider) - err := http.ListenAndServe(":8000", r) + err := http.ListenAndServe(settings.Endpoint, r) if err != nil { panic(err) } diff --git a/settings/settings.go b/settings/settings.go index 6e88584..6239703 100644 --- a/settings/settings.go +++ b/settings/settings.go @@ -1,6 +1,10 @@ package settings -import "encoding/json" +import ( + "encoding/json" + "os" + "path/filepath" +) const ( Local FileSystemType = iota @@ -26,3 +30,30 @@ func ParseSettings(data []byte) Settings { return settings } + +func LoadSettings() Settings { + workingDirectory, _ := os.Getwd() + path := filepath.Join(workingDirectory, "settings.json") + + // Load file and parse file + data, err := os.ReadFile(path) + + if err == nil { + return ParseSettings(data) + } + + // If file does not exist, create default settings + defaultSettings := Settings{ + Endpoint: "127.0.0.1:8000", + Token: "changeme", + FileSystem: FileSystemSettings{ + Type: Local, + BasePath: "assets", + }, + } + + serializedSettings, err := json.Marshal(defaultSettings) + os.WriteFile(path, serializedSettings, os.ModePerm) + + return defaultSettings +}