-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
83 lines (61 loc) · 1.43 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
package i18n
import (
"sync"
"golang.org/x/text/language"
)
// Cache stores translations in a map for fast access
type Cache struct {
lock sync.RWMutex
cache map[string]map[string]*Translation
}
// Clear translation cache
func (cache *Cache) Clear() {
cache.lock.Lock()
defer cache.lock.Unlock()
cache.cache = make(map[string]map[string]*Translation)
}
// Add translation to cache
func (cache *Cache) Add(translation *Translation) {
cache.lock.Lock()
defer cache.lock.Unlock()
if cache.cache == nil {
cache.cache = make(map[string]map[string]*Translation)
}
l := translation.Lang.String()
if _, ok := cache.cache[l]; !ok {
cache.cache[l] = make(map[string]*Translation)
}
cache.cache[l][translation.Key] = translation
}
// Get translation from cache
func (cache *Cache) Get(lang language.Tag, key string) *Translation {
cache.lock.RLock()
defer cache.lock.RUnlock()
if cache.cache == nil {
return nil
}
l := lang.String()
if _, ok := cache.cache[l]; !ok {
return nil
}
if _, ok := cache.cache[l][key]; !ok {
return nil
}
return cache.cache[l][key]
}
// Delete translation from cache
func (cache *Cache) Delete(translation *Translation) {
cache.lock.Lock()
defer cache.lock.Unlock()
if cache.cache == nil {
return
}
l := translation.Lang.String()
if _, ok := cache.cache[l]; !ok {
return
}
if _, ok := cache.cache[l][translation.Key]; !ok {
return
}
delete(cache.cache[l], translation.Key)
}