-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataLayer.go
117 lines (100 loc) · 2.1 KB
/
dataLayer.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"runtime/debug"
"sync"
)
var (
DiskLock = sync.Mutex{}
basePath = "./mdata"
fileType = "json"
)
type FileType string
var (
DataCenterFile FileType = "datacenter"
RowFile FileType = "row"
RackFile FileType = "rack"
UnitFile FileType = "unit"
ConnectionFile FileType = "connection"
NetworkFile FileType = "network"
)
type StoragePath string
var (
DataCenterPath StoragePath = "datacenters"
RowsPath StoragePath = "rows"
RackPath StoragePath = "racks"
UnitPath StoragePath = "units"
ConnectionPath StoragePath = "connections"
NetworkPath StoragePath = "networks"
)
func GetObjectPath(p StoragePath, t FileType, id int) string {
return fmt.Sprintf(
"%s%s%s%s%s_%d.%s",
basePath,
string(os.PathSeparator),
p,
string(os.PathSeparator),
t,
id,
fileType,
)
}
func GetDirPath(p StoragePath, t FileType) string {
return fmt.Sprintf(
"%s%s%s%s",
basePath,
string(os.PathSeparator),
p,
string(os.PathSeparator),
)
}
func WriteObject(p StoragePath, t FileType, id int, object interface{}) (err error) {
DiskLock.Lock()
defer func() {
r := recover()
if r != nil {
log.Println(r, string(debug.Stack()))
}
DiskLock.Unlock()
}()
dirErr := os.MkdirAll(GetDirPath(p, t), 0o777)
if dirErr != nil {
return dirErr
}
data, encodingErr := json.Marshal(object)
if encodingErr != nil {
return encodingErr
}
return os.WriteFile(GetObjectPath(p, t, id), data, 0o777)
}
func GetObject(p StoragePath, t FileType, id int) (data []byte, err error) {
data, err = os.ReadFile(GetObjectPath(p, t, id))
if err != nil {
return nil, err
}
return
}
func GetObjectFullPath(path string) (data []byte, err error) {
data, err = os.ReadFile(path)
if err != nil {
return nil, err
}
return
}
func GetObjects(startPath string, action func(objectPath string)) (err error) {
walkFunc := func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
action(path)
}
return nil
}
filepath.WalkDir(startPath, walkFunc)
return err
}