From b1d92b395322f2164ccfb44b0f7caebbaece6b62 Mon Sep 17 00:00:00 2001 From: jwijenbergh Date: Fri, 22 Apr 2022 16:29:59 +0200 Subject: Refactor: Restructure project - Add an internal folder where all the internal code lives - Make a state.go and state_test.go for the public interface This gives a more clear separation between functions and modules. It also makes this a more typical Go project setup. --- internal/config.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 internal/config.go (limited to 'internal/config.go') diff --git a/internal/config.go b/internal/config.go new file mode 100644 index 0000000..47f773e --- /dev/null +++ b/internal/config.go @@ -0,0 +1,43 @@ +package internal + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "path" +) + +type Config struct { + Name string + Directory string +} + +func (config *Config) Init(name string, directory string) { + config.Name = name + config.Directory = directory +} + +func (config *Config) GetFilename() string { + pathString := path.Join(config.Directory, config.Name) + return fmt.Sprintf("%s.json", pathString) +} + +func (config *Config) Save(readStruct interface{}) error { + configDirErr := EnsureDirectory(config.Directory) + if configDirErr != nil { + return configDirErr + } + jsonString, marshalErr := json.Marshal(readStruct) + if marshalErr != nil { + return marshalErr + } + return ioutil.WriteFile(config.GetFilename(), jsonString, 0o644) +} + +func (config *Config) Load(writeStruct interface{}) error { + bytes, readErr := ioutil.ReadFile(config.GetFilename()) + if readErr != nil { + return readErr + } + return json.Unmarshal(bytes, writeStruct) +} -- cgit v1.2.3