cache.go 596 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package memory_cache
  2. import (
  3. "sync"
  4. )
  5. type Cache struct {
  6. mu sync.RWMutex
  7. items map[string]interface{}
  8. }
  9. func NewCache() *Cache {
  10. return &Cache{
  11. items: make(map[string]interface{}),
  12. }
  13. }
  14. func (c *Cache) Set(key string, value interface{}) {
  15. c.mu.Lock()
  16. defer c.mu.Unlock()
  17. c.items[key] = value
  18. }
  19. func (c *Cache) Get(key string) (interface{}, bool) {
  20. c.mu.RLock()
  21. defer c.mu.RUnlock()
  22. item, found := c.items[key]
  23. return item, found
  24. }
  25. func (c *Cache) Delete(key string) {
  26. c.mu.Lock()
  27. defer c.mu.Unlock()
  28. if _, found := c.items[key]; found {
  29. delete(c.items, key)
  30. }
  31. }