loadCacheFiles loads all existing cache files into memory.
()
| 91 | |
| 92 | // loadCacheFiles loads all existing cache files into memory. |
| 93 | func (c *FileCache) loadCacheFiles() error { |
| 94 | files, err := os.ReadDir(c.dir) |
| 95 | if err != nil { |
| 96 | return fmt.Errorf("failed to read cache directory: %w", err) |
| 97 | } |
| 98 | |
| 99 | for _, file := range files { |
| 100 | if file.IsDir() || filepath.Ext(file.Name()) != ".json" { |
| 101 | continue |
| 102 | } |
| 103 | |
| 104 | key := file.Name()[:len(file.Name())-5] // Remove .json extension |
| 105 | |
| 106 | // Read the file |
| 107 | data, err := os.ReadFile(filepath.Join(c.dir, file.Name())) |
| 108 | if err != nil { |
| 109 | getCacheLogger().Debug("Warning: Failed to read cache file %s: %v", file.Name(), err) |
| 110 | |
| 111 | continue |
| 112 | } |
| 113 | |
| 114 | // Parse the item |
| 115 | var item CacheItem |
| 116 | if err := json.Unmarshal(data, &item); err != nil { |
| 117 | getCacheLogger().Debug("Warning: Failed to parse cache file %s: %v", file.Name(), err) |
| 118 | |
| 119 | continue |
| 120 | } |
| 121 | |
| 122 | // Check if the item is expired |
| 123 | if item.TTL > 0 && time.Now().Unix()-item.Timestamp > item.TTL { |
| 124 | // Item is expired, remove the file |
| 125 | if err := os.Remove(filepath.Join(c.dir, file.Name())); err != nil { |
| 126 | getCacheLogger().Debug("Warning: Failed to remove expired cache file %s: %v", file.Name(), err) |
| 127 | } |
| 128 | |
| 129 | continue |
| 130 | } |
| 131 | |
| 132 | // Add to in-memory cache with LRU tracking |
| 133 | entry := &lruEntry{key: key, item: &item} |
| 134 | element := c.lruList.PushFront(entry) |
| 135 | c.inMemory[key] = element |
| 136 | } |
| 137 | |
| 138 | return nil |
| 139 | } |
| 140 | |
| 141 | // Get retrieves data from the cache and updates LRU order. |
| 142 | func (c *FileCache) Get(key string, dest interface{}) (bool, error) { |
no test coverage detected