initial commit
This commit is contained in:
63
lib/cache.go
Normal file
63
lib/cache.go
Normal file
@@ -0,0 +1,63 @@
|
||||
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})
|
||||
}
|
||||
Reference in New Issue
Block a user