-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
206 lines (181 loc) · 4.37 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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/spf13/afero"
)
var (
BackUpFrequency = time.Second * 1
BackUpDir = ".cloudbase"
FileName = "data"
Data = make(map[string][]interface{}, 0)
paths []string
fs = afero.NewOsFs()
BackUpTicker *time.Ticker
)
func main() {
exists, err := afero.Exists(fs, BackUpDir)
if err != nil {
log.Fatalln(err)
return
}
if !exists {
err = fs.MkdirAll(BackUpDir, 0740)
if err != nil {
log.Fatalln(err)
return
}
} else {
files, err := afero.ReadDir(fs, BackUpDir)
if err != nil {
fmt.Println("Cannot read dir:", err)
}
if err == nil && len(files) > 0 {
var latest, which int
for i, f := range files {
nameArr := strings.Split(f.Name(), ".")
if !strings.Contains(f.Name(), "cloudbase") {
continue
}
time, err := strconv.Atoi(nameArr[0])
if err != nil {
log.Println("Cannot convert filename to time:", err)
return
}
if time > latest {
latest = time
which = i
}
path := filepath.Join(BackUpDir, f.Name())
paths = append(paths, path)
}
path := filepath.Join(BackUpDir, files[which].Name())
file, err := fs.Open(path)
if err != nil {
log.Println("Cannot open file:", err)
return
}
err = json.NewDecoder(file).Decode(&Data)
if err != nil {
log.Println("Cannot read file:", err)
return
}
log.Println("Read backup file")
}
}
router := httprouter.New()
router.POST("/:key", HandlePush)
router.PUT("/:key/:name/:value", HandleModify)
router.GET("/:key", HandleGet)
BackUpTicker = time.NewTicker(BackUpFrequency)
go BackUpInterval()
log.Println("Starting cloudbase on localhost:7777")
log.Fatal(http.ListenAndServe(":7777", clean(router)))
}
func clean(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Header)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", r.Header.Get("Access-Control-Request-Method"))
handler.ServeHTTP(w, r)
})
}
func BackUpInterval() {
for t := range BackUpTicker.C {
log.Println("Save at", t)
BackUp()
Clean()
}
}
func JSONRead(r io.Reader) (interface{}, error) {
var i interface{}
d := json.NewDecoder(r)
return i, d.Decode(&i)
}
func JSONWrite(w io.Writer, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
func HandlePush(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
data, err := JSONRead(r.Body)
if err != nil {
log.Println("Cannot decode request:", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
return
}
Push(key, data)
}
func HandleGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
JSONWrite(w, Get(ps.ByName("key")))
}
func HandleModify(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
name := ps.ByName("name")
value := ps.ByName("value")
change, err := JSONRead(r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
return
}
Modify(key, name, value, change)
}
func Push(key string, d interface{}) {
Data[key] = append(Data[key], d)
log.Println("Pushed", d, "to", key)
}
func Get(key string) interface{} {
log.Println("Asked for", key)
return Data[key]
}
func Modify(key, name string, value string, change interface{}) {
for i, v := range Data[key] {
if reflect.ValueOf(v).MapIndex(reflect.ValueOf(name)).Interface() == reflect.ValueOf(value).Interface() {
log.Println("Modified", key, "with", name, value)
Data[key][i] = change
}
}
}
func BackUp() {
name := fmt.Sprintf("%d.cloudbase", time.Now().Unix())
path := filepath.Join(BackUpDir, name)
file, err := fs.Create(path)
if err != nil {
log.Println("Cannot save:", err)
return
}
err = JSONWrite(file, Data)
if err != nil {
log.Println("Cannot save:", err)
return
}
paths = append(paths, path)
}
func Clean() {
if len(paths) > 60 {
for _, p := range paths[1:] {
err := fs.Remove(p)
if err != nil {
log.Println("Cannot clean", p, ":", err)
}
log.Println("Cleaned", p)
}
paths = []string{}
}
}