package cache import ( "sync" "time" ) type entry struct { value string expires time.Time } type Cache struct { ttl time.Duration mu sync.RWMutex values map[string]entry } func New(ttl time.Duration) *Cache { if ttl <= 0 { ttl = time.Hour } return &Cache{ ttl: ttl, values: make(map[string]entry), } } func (c *Cache) Get(key string) (string, bool) { c.mu.RLock() e, ok := c.values[key] c.mu.RUnlock() if !ok { return "", false } if time.Now().After(e.expires) { c.mu.Lock() delete(c.values, key) c.mu.Unlock() return "", false } return e.value, true } func (c *Cache) Set(key string, value string) { c.mu.Lock() c.values[key] = entry{ value: value, expires: time.Now().Add(c.ttl), } c.mu.Unlock() } func (c *Cache) ClearExpired() int { now := time.Now() c.mu.Lock() removed := 0 for k, v := range c.values { if now.After(v.expires) { delete(c.values, k) removed++ } } c.mu.Unlock() return removed } func (c *Cache) TTL() time.Duration { return c.ttl }