feat: cache
This commit is contained in:
parent
ef80892aa5
commit
5cdbbd2296
3 changed files with 148 additions and 0 deletions
77
cache/file.go
vendored
Normal file
77
cache/file.go
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
package cache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.nakama.town/fmartingr/gotoolkit/model"
|
||||
)
|
||||
|
||||
var _ model.Cache = (*FileCache)(nil)
|
||||
|
||||
type FileCache struct {
|
||||
path string
|
||||
}
|
||||
|
||||
func (c *FileCache) Get(key string) (result any, err error) {
|
||||
path := filepath.Join(c.path, key)
|
||||
|
||||
contents, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) {
|
||||
return result, model.ErrCacheKeyDontExist
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
return contents, nil
|
||||
}
|
||||
|
||||
func (c *FileCache) GetWithExpiry(key string, expiration time.Duration) (result any, err error) {
|
||||
path := filepath.Join(c.path, key)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return result, model.ErrCacheKeyDontExist
|
||||
}
|
||||
|
||||
if info.ModTime().Add(expiration).Before(time.Now()) {
|
||||
c.Delete(key)
|
||||
return result, model.ErrCacheKeyDontExist
|
||||
}
|
||||
|
||||
return c.Get(key)
|
||||
}
|
||||
|
||||
func (c *FileCache) Set(key string, value any) error {
|
||||
path := filepath.Join(c.path, key)
|
||||
|
||||
if err := os.WriteFile(path, value.([]byte), 0766); err != nil {
|
||||
return fmt.Errorf("error writting cache file: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *FileCache) Delete(key string) error {
|
||||
path := filepath.Join(c.path, key)
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
func NewFileCache(folderName string) (*FileCache, error) {
|
||||
userCacheDir, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not retrieve user cache directory: %w", err)
|
||||
}
|
||||
path := filepath.Join(userCacheDir, folderName)
|
||||
|
||||
if err := os.MkdirAll(path, 0755); err != nil {
|
||||
return nil, fmt.Errorf("couldn't create cache directory: %w", err)
|
||||
}
|
||||
|
||||
return &FileCache{
|
||||
path: path,
|
||||
}, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue