Problem Outline:
This code snippet loads data from files into a map during startup. However, it faces an issue when encountering errors during file loading. The issue arises because the code clears the map before loading each new file, which can lead to data loss if an error occurs and the previous map state is not preserved.
Proposed Solution:
To overcome this issue, a more straightforward approach can be adopted:
Implementation:
<code class="go">type CustomerConfig struct { Data map[string]bool LoadedAt time.Time } func loadConfig() (*CustomerConfig, error) { cfg := &CustomerConfig{ Data: map[string]bool{}, LoadedAt: time.Now(), } // Load files and populate cfg.Data // Return error if encountered return cfg, nil } type ConfigCache struct { configMu sync.RWMutex config *CustomerConfig closeCh chan struct{} } func NewConfigCache() (*ConfigCache, error) { cfg, err := loadConfig() if err != nil { return nil, err } cc := &ConfigCache{ config: cfg, closeCh: make(chan struct{}), } go cc.refresher() return cc, nil } func (cc *ConfigCache) refresher() { ticker := time.NewTicker(1 * time.Minute) defer ticker.Stop() for { select { case <-ticker.C: // Check for changes changes := false // Implement logic to detect changes if !changes { continue } cfg, err := loadConfig() if err != nil { log.Printf("Failed to load config: %v", err) continue } cc.configMu.Lock() cc.config = cfg cc.configMu.Unlock() case <-cc.closeCh: return } } } func (cc *ConfigCache) Stop() { close(cc.closeCh) } func (cc *ConfigCache) GetConfig() *CustomerConfig { cc.configMu.RLock() defer cc.configMu.RUnlock() return cc.config }</code>
Usage:
<code class="go">cc, err := NewConfigCache() if err != nil { // Handle error } cfg := cc.GetConfig() // Access the latest configuration</code>
The above is the detailed content of The title could be: **How to Handle Errors During File Loading in a Data Map?**. For more information, please follow other related articles on the PHP Chinese website!