Skip to content

Instantly share code, notes, and snippets.

@gadelkareem
Created March 2, 2018 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gadelkareem/379b640eeb649a13b174198efee94a17 to your computer and use it in GitHub Desktop.
Save gadelkareem/379b640eeb649a13b174198efee94a17 to your computer and use it in GitHub Desktop.
Simple Golang file cache
package utilities
import (
"path/filepath"
"os"
"sync"
"io/ioutil"
"time"
"github.com/vmihailenco/msgpack"
)
type fileCache struct {
fileMu sync.RWMutex
path string
ttl time.Duration
}
var fCache *fileCache
func FileCache() *fileCache {
if fCache == nil {
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
path += "/tmp"
fCache = NewFileCache(path, 24*time.Hour)
}
return fCache
}
func NewFileCache(path string, ttl time.Duration) *fileCache {
os.MkdirAll(path, os.ModePerm)
return &fileCache{
path: path,
ttl: ttl,
}
}
func (c *fileCache) Load(fileName string, f interface{}) error {
filePath := c.path + "/" + fileName
fileInfo, _ := os.Stat(filePath)
if fileInfo == nil || fileInfo.ModTime().Add(c.ttl).Before(time.Now()) {
return nil
}
data, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
return msgpack.Unmarshal(data, f)
}
func (c *fileCache) Save(f interface{}, fileName string) error {
c.fileMu.Lock()
defer c.fileMu.Unlock()
data, err := msgpack.Marshal(f)
if err != nil {
return err
}
return ioutil.WriteFile(c.path+"/"+fileName, data, 0666)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment