hashStorage.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package global
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "regexp"
  6. "sync"
  7. "time"
  8. )
  9. type HashEntry struct {
  10. Hash string
  11. Value string
  12. Timestamp time.Time
  13. }
  14. type HashStorage struct {
  15. sync.RWMutex
  16. Data map[string]HashEntry
  17. Expiration time.Duration
  18. }
  19. func NewHashStorage(expiration time.Duration) *HashStorage {
  20. return &HashStorage{
  21. Data: make(map[string]HashEntry),
  22. Expiration: expiration,
  23. }
  24. }
  25. func (h *HashStorage) SaveHash(query string) string {
  26. h.Lock()
  27. defer h.Unlock()
  28. md5Hash := md5.Sum([]byte(query))
  29. md5HashString := hex.EncodeToString(md5Hash[:])
  30. entry := HashEntry{
  31. Hash: md5HashString,
  32. Value: query,
  33. Timestamp: time.Now(),
  34. }
  35. h.Data[md5HashString] = entry
  36. return md5HashString
  37. }
  38. func (h *HashStorage) GetValue(hash string) (string, bool) {
  39. h.RLock()
  40. defer h.RUnlock()
  41. entry, exists := h.Data[hash]
  42. return entry.Value, exists
  43. }
  44. func (h *HashStorage) IsMD5(hash string) bool {
  45. match, _ := regexp.MatchString("^[a-f0-9]{32}$", hash)
  46. return match
  47. }
  48. func (h *HashStorage) RemoveExpiredHashes() {
  49. h.Lock()
  50. defer h.Unlock()
  51. now := time.Now()
  52. for hash, entry := range h.Data {
  53. if now.Sub(entry.Timestamp) > h.Expiration {
  54. delete(h.Data, hash)
  55. }
  56. }
  57. }
  58. func (h *HashStorage) Reset() {
  59. h.Lock()
  60. defer h.Unlock()
  61. h.Data = make(map[string]HashEntry)
  62. }