Set stores data in the cache.
(key string, data interface{}, ttl time.Duration)
| 187 | |
| 188 | // Set stores data in the cache. |
| 189 | func (c *FileCache) Set(key string, data interface{}, ttl time.Duration) error { |
| 190 | c.mutex.Lock() |
| 191 | defer c.mutex.Unlock() |
| 192 | |
| 193 | // Marshal data to JSON once (avoids double marshaling on Get) |
| 194 | jsonData, err := json.Marshal(data) |
| 195 | if err != nil { |
| 196 | return fmt.Errorf("failed to marshal data: %w", err) |
| 197 | } |
| 198 | |
| 199 | // Create cache item with pre-marshaled JSON |
| 200 | item := &CacheItem{ |
| 201 | Data: jsonData, |
| 202 | Timestamp: time.Now().Unix(), |
| 203 | TTL: int64(ttl.Seconds()), |
| 204 | } |
| 205 | |
| 206 | // Check if item already exists, update it if so |
| 207 | if element, exists := c.inMemory[key]; exists { |
| 208 | entry := element.Value.(*lruEntry) |
| 209 | entry.item = item |
| 210 | c.lruList.MoveToFront(element) |
| 211 | } else { |
| 212 | // Add new item to cache |
| 213 | entry := &lruEntry{key: key, item: item} |
| 214 | element := c.lruList.PushFront(entry) |
| 215 | c.inMemory[key] = element |
| 216 | |
| 217 | // Evict least recently used item if cache is full |
| 218 | if c.maxSize > 0 && c.lruList.Len() > c.maxSize { |
| 219 | c.evictLRU() |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // If persisted, write to file |
| 224 | if c.persisted { |
| 225 | // Convert to JSON |
| 226 | bytes, err := json.Marshal(item) |
| 227 | if err != nil { |
| 228 | return fmt.Errorf("failed to marshal cache item: %w", err) |
| 229 | } |
| 230 | |
| 231 | // Write to file |
| 232 | filePath := filepath.Join(c.dir, key+".json") |
| 233 | if err := os.WriteFile(filePath, bytes, 0o600); err != nil { |
| 234 | return fmt.Errorf("failed to write cache file: %w", err) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | getCacheLogger().Debug("Cached item: %s with TTL %v", key, ttl) |
| 239 | |
| 240 | return nil |
| 241 | } |
| 242 | |
| 243 | // evictLRU removes the least recently used item from the cache. |
| 244 | // Must be called with mutex held. |