This repository was archived by the owner on Sep 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
94 lines (83 loc) · 2.17 KB
/
cache.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
package backend
import (
"encoding/json"
"log"
"time"
)
// CacheGet retrieves a cache value
func CacheGet(token, key string, v interface{}) error {
var s string
if err := Get(token, "/sudo/cache?key="+key, &s); err != nil {
return err
}
return json.Unmarshal([]byte(s), v)
}
// CacheSet sets a cache value
func CacheSet(token, key string, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
data := new(struct {
Key string `json:"key"`
Value string `json:"value"`
})
data.Key = key
data.Value = string(b)
var ok bool
return Post(token, "/sudo/cache", data, &ok)
}
// WorkerTask is the function type needed for work queue action
type WorkerTask func(val string)
// WorkerQueue monitors a work queue each 5 seconds.
// If there's new work available it will call the WorkerTask function back.
// This function should be ran concurrently i.e. go backend.WorkerQueue()
func WorkerQueue(token, key string, worker WorkerTask) {
ticker := time.NewTicker(5 * time.Second)
for {
select {
case <-ticker.C:
go checkQueue(token, key, worker)
}
}
}
func checkQueue(token, key string, worker WorkerTask) {
var s string
if err := Get(token, "/sudo/cache?type=queue&key="+key, &s); err != nil {
log.Println("error while checking for worker queue: ", err)
}
if len(s) > 0 {
worker(s)
}
}
// QueueWork adds a work queue value that will be dequeue via WorkerQueue
func QueueWork(token, key, value string) error {
data := new(struct {
Key string `json:"key"`
Value string `json:"value"`
Type string `json:"type"`
})
data.Key = key
data.Value = value
data.Type = "queue"
var ok bool
return Post(token, "/sudo/cache", data, &ok)
}
// Publish sends a message to a channel (topic) where usually a server-side
// function will process the message.
func Publish(token, channel, typ string, data interface{}) error {
b, err := json.Marshal(data)
if err != nil {
return err
}
payload := new(struct {
Channel string `json:"channel"`
Type string `json:"type"`
Data string `json:"data"`
})
payload.Channel = channel
payload.Type = typ
payload.Data = string(b)
var status bool
return Post(token, "/publish", payload, &status)
}