-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
263 lines (207 loc) · 5.22 KB
/
main.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/jcelliott/lumber"
)
const Version = "1.0.0"
type (
Logger interface {
Fatal(string, ...interface{})
Error(string, ...interface{})
Warn(string, ...interface{})
Info(string, ...interface{})
Debug(string, ...interface{})
Trace(string, ...interface{})
}
Driver struct {
mutex sync.Mutex
mutexes map[string]*sync.Mutex
dir string
log Logger
}
)
type Options struct {
Logger
}
// Creates a database and returns the Driver we can use to interact with the DB
func New(dir string, options *Options) (*Driver, error) {
dir = filepath.Clean(dir)
opts := Options{}
if options != nil {
opts = *options
}
//creating a Logger
if opts.Logger == nil {
opts.Logger = lumber.NewConsoleLogger(lumber.INFO)
}
//creating a driver of type Driver
driver := Driver{
dir: dir,
mutexes: make(map[string]*sync.Mutex),
log: opts.Logger,
}
//check if database exists by passing the name of the directory
if _, err := os.Stat(dir); err == nil {
opts.Logger.Debug("Using '%s' (database already exists)\n", dir)
return &driver, nil
}
//database does not exists
opts.Logger.Debug("Creating the database at '%s' ...\n", dir)
return &driver, os.MkdirAll(dir, 0755)
}
func (d *Driver) Write(collection, resource string, v interface{}) error {
if collection == "" {
return fmt.Errorf("Missing collection!")
}
if resource == "" {
return fmt.Errorf("Missing resource!")
}
//only when the write function is completed then only it is unlock otherwise it wont allow anything to work with database
mutex := d.getOrCreateMutex(collection)
mutex.Lock()
defer mutex.Unlock()
dir := filepath.Join(d.dir, collection)
finalPath := filepath.Join(dir, resource+".json")
tempPath := finalPath + ".tmp"
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
b, err := json.MarshalIndent(v, "", "\t")
if err != nil {
return err
}
b = append(b, byte('\n'))
if err := ioutil.WriteFile(tempPath, b, 0644); err != nil {
return err
}
return os.Rename(tempPath, finalPath)
}
func (d *Driver) Read(collection, resource string, v interface{}) error {
if collection == "" {
return fmt.Errorf("Missing collection")
}
if resource == "" {
return fmt.Errorf("Missing resource")
}
record := filepath.Join(d.dir, collection, resource)
if _, err := stat(record); err != nil {
return err
}
b, err := ioutil.ReadFile(record + ".json")
if err != nil {
return err
}
return json.Unmarshal(b, &v)
}
func (d *Driver) ReadAll(collection string) ([]string, error) {
if collection == "" {
return nil, fmt.Errorf("Missing collection")
}
dir := filepath.Join(d.dir, collection)
if _, err := stat(dir); err != nil {
return nil, err
}
files, _ := ioutil.ReadDir(dir)
var records []string
for _, file := range files {
b, err := ioutil.ReadFile(filepath.Join(dir, file.Name()))
if err != nil {
return nil, err
}
records = append(records, string(b))
}
return records, nil
}
func (d *Driver) Delete(collection, resource string) error {
path := filepath.Join(collection, resource)
mutex := d.getOrCreateMutex(collection)
mutex.Lock()
mutex.Unlock()
dir := filepath.Join(d.dir, path)
switch fi, err := stat(dir); {
case fi == nil, err != nil:
return fmt.Errorf("Unable to find file or directory %v\n", path)
case fi.Mode().IsDir():
return os.RemoveAll(dir)
case fi.Mode().IsRegular():
return os.RemoveAll(dir + ".json")
}
return nil
}
func (d *Driver) getOrCreateMutex(collection string) *sync.Mutex {
d.mutex.Lock()
defer d.mutex.Unlock()
m, ok := d.mutexes[collection]
if !ok {
m = &sync.Mutex{}
d.mutexes[collection] = m
}
return m
}
//checks for files with a .json extension
func stat(path string) (fi os.FileInfo, err error) {
if fi, err = os.Stat(path); os.IsNotExist(err) {
fi, err = os.Stat(path + ".json")
}
return
}
type Address struct {
City string
// State string
// Country string
Pincode json.Number
}
type User struct {
Name string
Age json.Number
Contact string
Company string
Address Address
}
func main() {
dir := "./"
db, err := New(dir, nil)
if err != nil {
fmt.Println("Error", err)
}
employees := []User{
{"Linux", "12", "42567567", "linux", Address{"not appropriate", "12"}},
{"GoLang", "13", "12232343", "golang", Address{"not appropriate", "34"}},
{"K8s", "14", "41432343", "k8s", Address{"not appropriate", "56"}},
{"Docker", "15", "89982343", "docker", Address{"not appropriate", "78"}},
}
for _, value := range employees {
db.Write("users", value.Name, User{
Name: value.Name,
Age: value.Age,
Contact: value.Contact,
Company: value.Company,
Address: value.Address,
})
}
records, err := db.ReadAll("users")
if err != nil {
fmt.Println("Error", err)
}
fmt.Println(records)
allUsers := []User{}
for _, value := range records {
employeeFound := User{}
if err := json.Unmarshal([]byte(value), &employeeFound); err != nil {
fmt.Println("Error", err)
}
allUsers = append(allUsers, employeeFound)
}
fmt.Println(allUsers)
if err := db.Delete("users", "Linux"); err != nil {
fmt.Println("Error", err)
}
// if err := db.DeleteAll("user", ""); err != nil {
// fmt.Println("Error", err)
// }
}