-
Notifications
You must be signed in to change notification settings - Fork 3
/
cache_handlers.go
105 lines (96 loc) · 2.34 KB
/
cache_handlers.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
package uhttp
import (
"fmt"
"net/http"
)
var cacheDetailsHandler = func(u *UHTTP, middlewares ...Middleware) Handler {
return NewHandler(
WithMiddlewares(middlewares...),
WithOptionalGet(R{
"parsable": BOOL,
}),
WithGet(func(r *http.Request, ret *int) interface{} {
parsable := GetAsBool("parsable", r)
res := make(map[string]map[string]interface{})
u.cacheLock.RLock()
defer u.cacheLock.RUnlock()
for pattern, c := range u.cache {
res[pattern] = make(map[string]interface{})
keys := c.Keys()
for _, key := range keys {
if data, ok := c.GetByKey(key); ok {
if parsable != nil && *parsable {
stats, err := data.Stats(c)
if err != nil {
return err
}
res[pattern][fmt.Sprintf("%x", key)] = stats
} else {
res[pattern][fmt.Sprintf("%x", key)] = data.String()
}
}
}
}
return res
}),
)
}
var cacheClearHandler = func(u *UHTTP, middlewares ...Middleware) Handler {
return NewHandler(
WithMiddlewares(middlewares...),
WithOptionalGet(R{
"path": STRING,
"hash": STRING,
}),
WithPost(func(r *http.Request, ret *int) interface{} {
deletedEntries := 0
path := GetAsString("path", r)
hash := GetAsString("hash", r)
u.cacheLock.RLock()
defer u.cacheLock.RUnlock()
for _, c := range u.cache {
if path != nil && *path != c.HandlerPattern() {
continue
}
keys := c.Keys()
for _, key := range keys {
if hash != nil && *hash != key {
continue
}
c.Delete(key)
deletedEntries++
}
}
return map[string]int{
"deletedEntries": deletedEntries,
}
}),
)
}
var cacheSizeHandler = func(u *UHTTP, middlewares ...Middleware) Handler {
return NewHandler(
WithMiddlewares(middlewares...),
WithGet(func(r *http.Request, ret *int) interface{} {
res := make(map[string]map[string]interface{})
totalSize := uint64(0)
totalEntries := uint64(0)
u.cacheLock.RLock()
for pattern, cache := range u.cache {
size := cache.Size()
totalSize += size
entries := uint64(cache.Count())
totalEntries += entries
res[pattern] = map[string]interface{}{
"sizeInBytes": size,
"entries": entries,
}
}
u.cacheLock.RUnlock()
res["total"] = map[string]interface{}{
"sizeInBytes": totalSize,
"entries": totalEntries,
}
return res
}),
)
}