-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsondb.go
128 lines (95 loc) · 1.86 KB
/
jsondb.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
package jsondb
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"sync"
)
type base struct {
table map[string]interface{}
}
var db base
var filePath string
var lock sync.RWMutex
func checkErr(errMsg error) {
if errMsg != nil {
panic(errMsg)
fmt.Println("run error:", errMsg)
}
}
func isExist(fileName string) bool {
f, err := os.Stat(fileName)
if err == nil {
if !f.IsDir() {
return true
}
}
return false
}
// init json db
func initialize(fileName string) {
if path.Ext(fileName) != ".json" {
filePath = fileName + ".json"
} else {
filePath = fileName
}
exist := isExist(filePath)
if !exist {
f, err := os.Create(filePath)
defer f.Close()
checkErr(err)
}
db.syncData()
}
// sync file data to memo
func (this *base) syncData() {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0600)
defer f.Close()
checkErr(err)
contentByte, err := ioutil.ReadAll(f)
checkErr(err)
if len(contentByte) != 0 {
err = json.Unmarshal(contentByte, &this.table)
checkErr(err)
} else {
this.table = make(map[string]interface{})
}
}
// save data to File
func (this *base) Save() *base {
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer f.Close()
checkErr(err)
data, err := json.Marshal(this.table)
checkErr(err)
_, err = f.Write(data)
checkErr(err)
return this
}
// write data by key value
func (this *base) Write(key string, value interface{}) *base {
lock.Lock()
this.table[key] = value
lock.Unlock()
return this
}
// read data by key
func (this *base) Read(key string) interface{} {
return this.table[key]
}
// read all data
func (this *base) ReadAll() map[string]interface{} {
return this.table
}
// delete key
func (this *base) Del(key string) *base {
delete(this.table, key)
return this
}
// create db install
func Create(fileName string) *base {
initialize(fileName)
return &db
}