-
Notifications
You must be signed in to change notification settings - Fork 0
/
xfileCache.go
55 lines (48 loc) · 1.11 KB
/
xfileCache.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
package xfileCache
import (
"github.com/go-xe2/x/core/cmdenv"
"github.com/go-xe2/x/os/xcache"
"github.com/go-xe2/x/os/xfile"
"github.com/go-xe2/x/os/xfileNotify"
"time"
)
const (
mDEFAULT_CACHE_EXPIRE = 60
)
var (
cacheExpire = cmdenv.Get("x.xfileCache.expire", mDEFAULT_CACHE_EXPIRE).Int() * 1000
)
func GetContents(path string, duration ...interface{}) string {
return string(GetBinContents(path, duration...))
}
func GetBinContents(path string, duration ...interface{}) []byte {
k := cacheKey(path)
e := cacheExpire
if len(duration) > 0 {
e = getSecondExpire(duration[0])
}
r := xcache.GetOrSetFuncLock(k, func() interface{} {
b := xfile.GetBinContents(path)
if b != nil {
_, _ = xfileNotify.Add(path, func(event *xfileNotify.TEvent) {
xcache.Remove(k)
xfileNotify.Exit()
})
}
return b
}, e*1000)
if r != nil {
return r.([]byte)
}
return nil
}
func getSecondExpire(duration interface{}) int {
if d, ok := duration.(time.Duration); ok {
return int(d.Nanoseconds() / 1000000000)
} else {
return duration.(int)
}
}
func cacheKey(path string) string {
return "x.xfileCache:" + path
}