blob: 099a54ed65d17212fc885f621253af85e73ba7cc (
plain)
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
|
package global
import (
"crypto/md5"
"encoding/hex"
"sync"
"time"
)
type HashEntry struct {
Hash string
Value string
Timestamp time.Time
}
type HashStorage struct {
sync.RWMutex
Data map[string]HashEntry
Expiration time.Duration
ForceSave bool
}
func NewHashStorage(expiration time.Duration, forceSave bool) *HashStorage {
return &HashStorage{
Data: make(map[string]HashEntry),
Expiration: expiration,
ForceSave: forceSave,
}
}
func (h *HashStorage) AddHash(query string) string {
if h.ForceSave {
return h.saveValue(query)
}
// we only need to hash for more than 64 chars by default
if len(query) <= 64 {
return query
}
return h.saveValue(query)
}
func (h *HashStorage) saveValue(query string) string {
h.Lock()
defer h.Unlock()
md5Hash := md5.Sum([]byte(query))
md5HashString := hex.EncodeToString(md5Hash[:])
entry := HashEntry{
Hash: md5HashString,
Value: query,
Timestamp: time.Now(),
}
h.Data[md5HashString] = entry
return md5HashString
}
func (h *HashStorage) GetValue(hash string) string {
h.RLock()
defer h.RUnlock()
entry, exists := h.Data[hash]
if !exists {
return hash
}
return entry.Value
}
func (h *HashStorage) RemoveExpiredHashes() {
h.Lock()
defer h.Unlock()
now := time.Now()
for hash, entry := range h.Data {
if now.Sub(entry.Timestamp) > h.Expiration {
delete(h.Data, hash)
}
}
}
func (h *HashStorage) Reset() {
h.Lock()
defer h.Unlock()
h.Data = make(map[string]HashEntry)
}
|