2023-05-20 18:59:28 +03:00
|
|
|
package global
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
2023-05-20 20:16:42 +03:00
|
|
|
"regexp"
|
2023-05-20 18:59:28 +03:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HashEntry struct {
|
|
|
|
Hash string
|
|
|
|
Value string
|
|
|
|
Timestamp time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
type HashStorage struct {
|
|
|
|
sync.RWMutex
|
|
|
|
Data map[string]HashEntry
|
|
|
|
Expiration time.Duration
|
|
|
|
}
|
|
|
|
|
2023-05-21 07:03:08 +03:00
|
|
|
func NewHashStorage(expiration time.Duration) *HashStorage {
|
2023-05-20 18:59:28 +03:00
|
|
|
return &HashStorage{
|
|
|
|
Data: make(map[string]HashEntry),
|
|
|
|
Expiration: expiration,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-21 07:03:08 +03:00
|
|
|
func (h *HashStorage) SaveHash(query string) string {
|
2023-05-20 18:59:28 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-05-21 07:03:08 +03:00
|
|
|
func (h *HashStorage) GetValue(hash string) (string, bool) {
|
2023-05-20 18:59:28 +03:00
|
|
|
h.RLock()
|
|
|
|
defer h.RUnlock()
|
|
|
|
|
|
|
|
entry, exists := h.Data[hash]
|
2023-05-21 07:03:08 +03:00
|
|
|
|
|
|
|
return entry.Value, exists
|
2023-05-20 20:16:42 +03:00
|
|
|
}
|
|
|
|
|
2023-05-21 07:03:08 +03:00
|
|
|
func (h *HashStorage) IsMD5(hash string) bool {
|
2023-05-20 20:16:42 +03:00
|
|
|
match, _ := regexp.MatchString("^[a-f0-9]{32}$", hash)
|
|
|
|
return match
|
2023-05-20 18:59:28 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|