initial commit
This commit is contained in:
80
lib/cache.go
Normal file
80
lib/cache.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
|
||||
const cacheFile = "cache.json"
|
||||
|
||||
type CacheItem struct {
|
||||
Fetcher string
|
||||
Value string
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
Items []CacheItem
|
||||
}
|
||||
|
||||
func (c *Cache) Update(fetcher string, value string) {
|
||||
for i := range c.Items {
|
||||
if c.Items[i].Fetcher == fetcher {
|
||||
c.Items[i].Value = value
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Items = append(c.Items, CacheItem{
|
||||
Fetcher: fetcher,
|
||||
Value: value,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Cache) Get(fetcher string) (string, bool) {
|
||||
for _, item := range c.Items {
|
||||
if item.Fetcher == fetcher {
|
||||
return item.Value, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (c *Cache) Has(fetcher string) bool {
|
||||
_, found := c.Get(fetcher)
|
||||
return found
|
||||
}
|
||||
|
||||
func (c *Cache) IsChanged(fetcher string, value string) bool {
|
||||
cachedValue, found := c.Get(fetcher)
|
||||
if !found || cachedValue != value {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Cache) TryUpdate(fetcher string, value string) bool {
|
||||
if c.IsChanged(fetcher, value) {
|
||||
c.Update(fetcher, value)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Cache) Load() {
|
||||
f, err := os.Open(cacheFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
_ = json.NewDecoder(f).Decode(&c.Items)
|
||||
}
|
||||
|
||||
func (c *Cache) Save() {
|
||||
f, err := os.Create(cacheFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
_ = json.NewEncoder(f).Encode(c.Items)
|
||||
}
|
||||
Reference in New Issue
Block a user