app/storage: Enhancement: Set path with member function rather than

directly

Signed-off-by: Thomas Klaehn <tkl@blackfinn.de>
This commit is contained in:
2025-08-15 09:02:33 +02:00
parent 9cf9fb7263
commit ce31b61b1b
2 changed files with 17 additions and 9 deletions

View File

@@ -27,7 +27,7 @@ func init() {
} }
func SetConfigFilePath(path string) { func SetConfigFilePath(path string) {
store.Path = path store.SetPath(path)
res, err := store.Read() res, err := store.Read()
if err != nil { if err != nil {
logger.Print("unable to read config") logger.Print("unable to read config")

View File

@@ -1,13 +1,14 @@
package storage package storage
import ( import (
"errors"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
) )
type Storage struct { type Storage struct {
Path string path string
} }
var ( var (
@@ -18,17 +19,24 @@ func init() {
logger.SetFlags(log.Llongfile | log.Ltime) logger.SetFlags(log.Llongfile | log.Ltime)
} }
func (storage Storage) Read() ([]byte, error) { func (s *Storage) SetPath(path string) {
data, err := os.ReadFile(storage.Path) s.path = path
}
func (s Storage) Read() ([]byte, error) {
if len(s.path) == 0 {
return nil, errors.New("path not set")
}
data, err := os.ReadFile(s.path)
if err != nil { if err != nil {
logger.Printf("unable to read %s (%s)", storage.Path, err.Error()) logger.Printf("unable to read %s (%s)", s.path, err.Error())
return nil, err return nil, err
} }
return data, nil return data, nil
} }
func (storage Storage) Write(data []byte) error { func (s Storage) Write(data []byte) error {
dir := filepath.Dir(storage.Path) dir := filepath.Dir(s.path)
_, err := os.Stat(dir) _, err := os.Stat(dir)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
@@ -42,9 +50,9 @@ func (storage Storage) Write(data []byte) error {
return err return err
} }
} }
err = os.WriteFile(storage.Path, data, 0644) err = os.WriteFile(s.path, data, 0644)
if err != nil { if err != nil {
logger.Printf("unable to store %s (%s)", storage.Path, err.Error()) logger.Printf("unable to store %s (%s)", s.path, err.Error())
} }
return nil return nil
} }