vegvisir/pkg/cache/route.go

80 lines
1.8 KiB
Go
Raw Permalink Normal View History

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package cache
import (
"encoding/json"
"log"
)
type RouteCache struct {
SourceUrl string
TargetUrl string
}
type RouteCacheManager struct {
datastore CacheDatastore
prefix string
ttl int
}
func NewRouteCacheManager(datastore CacheDatastore, ttl int) RouteCacheManager {
return RouteCacheManager{
datastore: datastore,
prefix: "route_",
ttl: ttl,
}
}
func (rm *RouteCacheManager) Save(name string, r RouteCache) bool {
if !rm.datastore.IsConnected() {
log.Println("Route-cache:", "Not connected to server")
return false
}
data, err := json.Marshal(r)
if err != nil {
log.Println("Route-cache", "JSON encode:", err)
return false
}
name = rm.prefix + name
err = rm.datastore.SetKey(name, data, rm.ttl)
if err != nil {
log.Println("Route-cache:", "Unable to save", name, err)
return false
}
return true
}
func (rm *RouteCacheManager) Load(name string) (bool, *RouteCache) {
if !rm.datastore.IsConnected() {
log.Println("Route-cache:", "Not connected to server")
return false, &RouteCache{}
}
name = rm.prefix + name
data, err := rm.datastore.GetKey(name)
if err != nil {
log.Println("Route-cache:", "Unable to load", name, err)
return false, &RouteCache{}
}
rc := &RouteCache{}
err = json.Unmarshal([]byte(data.(string)), &rc)
if err != nil {
log.Println("Route-cache:", "JSON decode:", err)
return false, &RouteCache{}
}
return true, rc
}