85 lines
1.9 KiB
Go
85 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"
|
|
)
|
|
|
|
// RouteCache struct
|
|
type RouteCache struct {
|
|
SourceURL string
|
|
TargetURL string
|
|
}
|
|
|
|
// RouteCacheManager class
|
|
type RouteCacheManager struct {
|
|
datastore Datastore
|
|
prefix string
|
|
ttl int
|
|
}
|
|
|
|
// NewRouteCacheManager function
|
|
func NewRouteCacheManager(datastore Datastore, ttl int) RouteCacheManager {
|
|
return RouteCacheManager{
|
|
datastore: datastore,
|
|
prefix: "route_",
|
|
ttl: ttl,
|
|
}
|
|
}
|
|
|
|
// Save function
|
|
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
|
|
}
|
|
|
|
// Load function
|
|
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
|
|
}
|