-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
70 lines (58 loc) · 1.34 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
package main
import (
"github.com/cfwidget/cfwidget/env"
"sync"
"time"
)
type CachedResponse struct {
Data interface{}
ExpireAt time.Time
Status int
ContentType string
}
var cacheTtl time.Duration
var memcache = sync.Map{}
func init() {
envCache := env.Get("CACHE_TTL")
cacheTtl = time.Hour
if envCache != "" {
var err error
cacheTtl, err = time.ParseDuration(envCache)
if err != nil {
panic(err)
}
}
go func() {
cleanCache()
}()
}
func GetFromCache(site, key string) (CachedResponse, bool) {
val, exists := memcache.Load(site + ":" + key)
if !exists {
return CachedResponse{}, false
}
res, ok := val.(CachedResponse)
if !ok || time.Now().After(res.ExpireAt) {
memcache.Delete(site + ":" + key)
return CachedResponse{}, false
}
return res, true
}
func SetInCache(site, key string, status int, contentType string, data interface{}) time.Time {
cache := CachedResponse{Data: data, Status: status, ExpireAt: time.Now().Add(cacheTtl), ContentType: contentType}
memcache.Store(site+":"+key, cache)
return cache.ExpireAt
}
func RemoveFromCache(site, key string) {
memcache.Delete(site + ":" + key)
}
func cleanCache() {
memcache.Range(func(k, v interface{}) bool {
res, ok := v.(CachedResponse)
if !ok || time.Now().After(res.ExpireAt) {
memcache.Delete(k)
return true
}
return true
})
}