Created
March 2, 2018 04:46
-
-
Save gadelkareem/379b640eeb649a13b174198efee94a17 to your computer and use it in GitHub Desktop.
Simple Golang file cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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