This repository was archived by the owner on May 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalstorage.go
90 lines (73 loc) · 2.21 KB
/
localstorage.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/robertkrimen/otto"
)
// LocalStorage object
type LocalStorage struct{}
var defaultData = []byte("{}")
func readDatastoreFile(filename string) map[string]string {
data, err := ioutil.ReadFile(filename)
if err != nil {
// creates empty file with empty object inside {}
err := ioutil.WriteFile(filename, defaultData, 0644)
if err != nil {
panic("fatal error creating datastore file")
}
data = defaultData
}
// parsing json
datamap := map[string]string{}
err = json.Unmarshal(data, &datamap)
if err != nil {
fmt.Println(err)
}
return datamap
}
func writeDatastoreFile(datamap map[string]string, filename string) {
datamapJSON, _ := json.Marshal(datamap)
err = ioutil.WriteFile(filename, datamapJSON, 0644)
if err != nil {
panic("fatal error creating datastore file")
}
}
func clearDatastoreFile(filename string) {
err := ioutil.WriteFile(filename, defaultData, 0644)
if err != nil {
panic("fatal error creating datastore file")
}
}
// SetItem -> JS usage: localStorage.setItem('lastname', 'Smith');
func (ls LocalStorage) SetItem(call otto.FunctionCall) otto.Value {
key := call.Argument(0).String()
value := call.Argument(1).String()
datamap := readDatastoreFile(config.Vertex.Datastore)
datamap[key] = value
writeDatastoreFile(datamap, config.Vertex.Datastore)
result, _ := vm.ToValue(true)
return result
}
// GetItem -> JS usage: localStorage.getItem('lastname');
func (ls LocalStorage) GetItem(call otto.FunctionCall) otto.Value {
key := call.Argument(0).String()
datamap := readDatastoreFile(config.Vertex.Datastore)
result, _ := vm.ToValue(datamap[key])
return result
}
// RemoveItem -> JS usage: localStorage.removeItem('lastname');
func (ls LocalStorage) RemoveItem(call otto.FunctionCall) otto.Value {
key := call.Argument(0).String()
datamap := readDatastoreFile(config.Vertex.Datastore)
delete(datamap, key)
writeDatastoreFile(datamap, config.Vertex.Datastore)
result, _ := vm.ToValue(datamap[key])
return result
}
// Clear -> JS usage: localStorage.clear();
func (ls LocalStorage) Clear(call otto.FunctionCall) otto.Value {
clearDatastoreFile(config.Vertex.Datastore)
result, _ := vm.ToValue(true)
return result
}