hashStorage.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package global
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "regexp"
  6. "sync"
  7. "time"
  8. )
  9. // HashEntry represents a stored hash entry with its value and timestamp.
  10. type HashEntry struct {
  11. Hash string // MD5 hash string
  12. Value string // Original value
  13. Timestamp time.Time // Time when the hash was created
  14. }
  15. // HashStorage provides thread-safe storage for hash-value pairs with expiration.
  16. type HashStorage struct {
  17. sync.RWMutex
  18. Data map[string]HashEntry // Map of hash to entry
  19. Expiration time.Duration // Expiration duration for entries
  20. }
  21. // NewHashStorage creates a new HashStorage instance with the specified expiration duration.
  22. func NewHashStorage(expiration time.Duration) *HashStorage {
  23. return &HashStorage{
  24. Data: make(map[string]HashEntry),
  25. Expiration: expiration,
  26. }
  27. }
  28. // SaveHash generates an MD5 hash for the given query string and stores it with a timestamp.
  29. func (h *HashStorage) SaveHash(query string) string {
  30. h.Lock()
  31. defer h.Unlock()
  32. md5Hash := md5.Sum([]byte(query))
  33. md5HashString := hex.EncodeToString(md5Hash[:])
  34. entry := HashEntry{
  35. Hash: md5HashString,
  36. Value: query,
  37. Timestamp: time.Now(),
  38. }
  39. h.Data[md5HashString] = entry
  40. return md5HashString
  41. }
  42. // GetValue retrieves the original value for the given hash, returning true if found.
  43. func (h *HashStorage) GetValue(hash string) (string, bool) {
  44. h.RLock()
  45. defer h.RUnlock()
  46. entry, exists := h.Data[hash]
  47. return entry.Value, exists
  48. }
  49. // IsMD5 checks if the given string is a valid 32-character MD5 hash.
  50. func (h *HashStorage) IsMD5(hash string) bool {
  51. match, _ := regexp.MatchString("^[a-f0-9]{32}$", hash)
  52. return match
  53. }
  54. // RemoveExpiredHashes removes all hash entries that have exceeded the expiration duration.
  55. func (h *HashStorage) RemoveExpiredHashes() {
  56. h.Lock()
  57. defer h.Unlock()
  58. now := time.Now()
  59. for hash, entry := range h.Data {
  60. if now.Sub(entry.Timestamp) > h.Expiration {
  61. delete(h.Data, hash)
  62. }
  63. }
  64. }
  65. // Reset clears all stored hash entries.
  66. func (h *HashStorage) Reset() {
  67. h.Lock()
  68. defer h.Unlock()
  69. h.Data = make(map[string]HashEntry)
  70. }