Get retrieves data from the cache and updates LRU order.
(key string, dest interface{})
| 140 | |
| 141 | // Get retrieves data from the cache and updates LRU order. |
| 142 | func (c *FileCache) Get(key string, dest interface{}) (bool, error) { |
| 143 | c.mutex.Lock() |
| 144 | defer c.mutex.Unlock() |
| 145 | |
| 146 | // Check if item exists in memory |
| 147 | element, exists := c.inMemory[key] |
| 148 | if !exists { |
| 149 | getCacheLogger().Debug("Cache miss for: %s", key) |
| 150 | |
| 151 | return false, nil |
| 152 | } |
| 153 | |
| 154 | entry := element.Value.(*lruEntry) |
| 155 | item := entry.item |
| 156 | |
| 157 | // Check if the item is expired |
| 158 | if item.TTL > 0 && time.Now().Unix()-item.Timestamp > item.TTL { |
| 159 | // Item is expired, remove it |
| 160 | c.lruList.Remove(element) |
| 161 | delete(c.inMemory, key) |
| 162 | getCacheLogger().Debug("Cache item expired: %s", key) |
| 163 | |
| 164 | // If persisted, remove the file |
| 165 | if c.persisted { |
| 166 | filePath := filepath.Join(c.dir, key+".json") |
| 167 | if err := os.Remove(filePath); err != nil && !os.IsNotExist(err) { |
| 168 | return false, fmt.Errorf("failed to remove expired cache file: %w", err) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | return false, nil |
| 173 | } |
| 174 | |
| 175 | // Move to front (most recently used) |
| 176 | c.lruList.MoveToFront(element) |
| 177 | |
| 178 | getCacheLogger().Debug("Cache hit for: %s", key) |
| 179 | |
| 180 | // Unmarshal the raw JSON directly into the destination (no double marshaling) |
| 181 | if err := json.Unmarshal(item.Data, dest); err != nil { |
| 182 | return false, fmt.Errorf("failed to unmarshal cache data: %w", err) |
| 183 | } |
| 184 | |
| 185 | return true, nil |
| 186 | } |
| 187 | |
| 188 | // Set stores data in the cache. |
| 189 | func (c *FileCache) Set(key string, data interface{}, ttl time.Duration) error { |