-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata.go
More file actions
81 lines (70 loc) · 1.55 KB
/
data.go
File metadata and controls
81 lines (70 loc) · 1.55 KB
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
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type DataBase struct {
Name string `json:"databasename"`
Tables map[string]map[string]string `json:"tables"`
}
func (d *DataBase) Init(_name string) {
d.Name = _name
d.Tables = map[string]map[string]string{}
}
func (d *DataBase) Set(_table string, _key string, _value string) {
dt, ok := d.Tables[_table]
if !ok {
dt = make(map[string]string)
d.Tables[_table] = dt
}
d.Tables[_table][_key] = _value
}
func (d *DataBase) Get(_table string, _key string) string {
if _key == "" {
bytes, _ := json.Marshal(d.Tables[_table])
return string(bytes)
} else {
return d.Tables[_table][_key]
}
}
func (d *DataBase) Del(_table string, _key string) {
delete(d.Tables[_table], _key)
}
func (d *DataBase) Dump() string {
bytes, _ := json.MarshalIndent(d, "", " ")
return string(bytes)
}
func (d *DataBase) Hash() string {
bytes, _ := json.Marshal(d)
return fmt.Sprintf("%x", md5.Sum(bytes))
}
func (d *DataBase) getFileName() string {
return (d.Name + ".JSONdb")
}
func (d *DataBase) Load() {
_, err := os.Stat(d.getFileName())
if os.IsNotExist(err) {
file, err := os.Create(d.Name)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
defer file.Close()
}
raw, err := ioutil.ReadFile(d.getFileName())
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
json.Unmarshal(raw, &d)
}
func (d *DataBase) Store() {
err := ioutil.WriteFile(d.getFileName(), []byte(d.Dump()), 0644)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}