vegvisir/pkg/cache/manager.go
Piotr Biernat f474a549c5
All checks were successful
continuous-integration/drone/push Build is passing
[dev] Memo goroutines cache
2021-11-06 01:49:56 +01:00

88 lines
1.9 KiB
Go

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package cache
import (
"encoding/json"
"log"
)
type Manager struct {
datastore CacheDatastore
prefix string
ttl int
}
func NewManager(datastore CacheDatastore, prefix string, ttl int) Manager {
return Manager{
datastore: datastore,
prefix: prefix,
ttl: ttl,
}
}
func (rm *Manager) Save(name string, r interface{}) bool { // FIXME second argument type( interface{} )
data, err := json.Marshal(r)
if err != nil {
log.Println("JSON:", err) // FIXME
return false
}
name = rm.prefix + name
err = rm.datastore.SetKey(name, string(data), rm.ttl)
if err != nil {
log.Println("Error saving cache item:", name) // FIXME
return false
}
return true
}
func (rm *Manager) Load(name string, output interface{}) (bool, interface{}) { // FIXME second return type( interface{} )
name = rm.prefix + name
data, err := rm.datastore.GetKey(name)
if err != nil {
log.Println("Cache item:", name, "not found")
return false, nil
}
var res interface{}
switch t := output.(type) {
default:
log.Printf("Unsupported cache type: %T", t)
return false, nil
case *ResponseCache:
res = &ResponseCache{}
rm.convertType(data, res)
return true, res.(*ResponseCache)
case *RouteCache:
res = &RouteCache{}
rm.convertType(data, res)
return true, res.(*RouteCache)
}
}
func (rm *Manager) convertType(data interface{}, output interface{}) interface{} {
err := json.Unmarshal([]byte(data.(string)), &output)
if err != nil {
log.Println("Converting error: ", err) // FIXME
return nil
}
return output
}