Files
social-updater/lib/cache.go
2026-05-12 16:42:53 +02:00

64 lines
997 B
Go

package lib
import (
"encoding/csv"
"os"
"strings"
)
type Cache struct {
filePath string
seen map[string]bool
}
func NewCache(filePath string) (*Cache, error) {
c := &Cache{
filePath: filePath,
seen: make(map[string]bool),
}
if err := c.load(); err != nil {
return nil, err
}
return c, nil
}
func (c *Cache) load() error {
f, err := os.Open(c.filePath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
defer f.Close()
records, err := csv.NewReader(f).ReadAll()
if err != nil {
return err
}
for _, record := range records {
if len(record) > 0 {
c.seen[strings.TrimSpace(record[0])] = true
}
}
return nil
}
func (c *Cache) Has(id string) bool {
return c.seen[id]
}
func (c *Cache) Add(id string) error {
c.seen[id] = true
f, err := os.OpenFile(c.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
return w.Write([]string{id})
}