-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
44 lines (34 loc) · 816 Bytes
/
Copy pathstorage.go
File metadata and controls
44 lines (34 loc) · 816 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
import (
"encoding/json"
"os"
"path/filepath"
)
type Storage[T any] struct {
FileName string
}
func NewStorage[T any](fileName string) *Storage[T] {
exePath, _ := os.Executable()
dir := filepath.Dir(exePath)
fullPath := filepath.Join(dir, fileName)
return &Storage[T]{FileName: fullPath}
}
func (s *Storage[T]) Save(data T) error {
fileData, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.FileName, fileData, 0644)
}
func (s *Storage[T]) Load(data *T) error {
// ✅ Step 1: ensure file exists
if _, err := os.Stat(s.FileName); os.IsNotExist(err) {
os.WriteFile(s.FileName, []byte("[]"), 0644)
}
// read file
fileData, err := os.ReadFile(s.FileName)
if err != nil {
return err
}
return json.Unmarshal(fileData, data)
}