-
-
Notifications
You must be signed in to change notification settings - Fork 356
/
storage_wasm.go
72 lines (56 loc) · 1.23 KB
/
storage_wasm.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
package app
import (
"encoding/json"
"sync"
"syscall/js"
"github.com/maxence-charriere/go-app/v7/pkg/errors"
)
func init() {
LocalStorage = newJSStorage("localStorage")
SessionStorage = newJSStorage("sessionStorage")
}
type jsStorage struct {
name string
mutex sync.RWMutex
}
func newJSStorage(name string) *jsStorage {
return &jsStorage{name: name}
}
func (s *jsStorage) Set(k string, v interface{}) (err error) {
defer func() {
r := recover()
if r != nil {
err = errors.New("setting storage value failed").
Tag("storage-type", s.name).
Tag("key", k).
Wrap(r.(js.Error))
}
}()
s.mutex.Lock()
defer s.mutex.Unlock()
b, err := json.Marshal(v)
if err != nil {
return err
}
Window().Get(s.name).Call("setItem", k, btos(b))
return nil
}
func (s *jsStorage) Get(k string, v interface{}) error {
s.mutex.RLock()
defer s.mutex.RUnlock()
item := Window().Get(s.name).Call("getItem", k)
if !item.Truthy() {
return nil
}
return json.Unmarshal(stob(item.String()), v)
}
func (s *jsStorage) Del(k string) {
s.mutex.Lock()
defer s.mutex.Unlock()
Window().Get(s.name).Call("removeItem", k)
}
func (s *jsStorage) Clear() {
s.mutex.Lock()
defer s.mutex.Unlock()
Window().Get(s.name).Call("clear")
}