2021-07-23 16:10:37 +02:00
|
|
|
// ___ ____ ___ ___
|
|
|
|
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
|
|
|
|
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
|
|
|
|
// \ / | _ | _ | \ / || __ | || ||\\
|
|
|
|
// \/ |___ |___ | \/ || ____| || || \\
|
|
|
|
//
|
|
|
|
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
|
|
|
|
// Repo: https://git.pbiernat.dev/golang/vegvisir
|
|
|
|
|
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ResponseCache struct {
|
|
|
|
URL string
|
|
|
|
Body string
|
|
|
|
// Headers map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
type ResponseCacheManager struct {
|
|
|
|
datastore CacheDatastore
|
|
|
|
prefix string
|
|
|
|
ttl int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewResponseCacheManager(datastore CacheDatastore, ttl int) ResponseCacheManager {
|
|
|
|
return ResponseCacheManager{
|
|
|
|
datastore: datastore,
|
|
|
|
prefix: "response_",
|
|
|
|
ttl: ttl,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
func (rm *ResponseCacheManager) Save(name string, r ResponseCache) bool {
|
|
|
|
if !rm.datastore.IsConnected() {
|
|
|
|
log.Println("Response-cache:", "Not connected to server")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-07-23 16:10:37 +02:00
|
|
|
data, err := json.Marshal(r)
|
|
|
|
if err != nil {
|
2021-07-24 17:46:22 +02:00
|
|
|
log.Println("Response-cache", "JSON encode:", err)
|
|
|
|
return false
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
name = rm.prefix + name
|
|
|
|
err = rm.datastore.SetKey(name, string(data), rm.ttl)
|
|
|
|
if err != nil {
|
2021-07-24 17:46:22 +02:00
|
|
|
log.Println("Response-cache:", err, name) // FIXME
|
|
|
|
return false
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
2021-07-24 17:46:22 +02:00
|
|
|
|
|
|
|
return true
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) {
|
2021-07-24 17:46:22 +02:00
|
|
|
if !rm.datastore.IsConnected() {
|
|
|
|
log.Println("Response-cache:", "Not connected to server")
|
|
|
|
return false, &ResponseCache{}
|
|
|
|
}
|
2021-07-23 16:10:37 +02:00
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
name = rm.prefix + name
|
2021-07-23 16:10:37 +02:00
|
|
|
data, err := rm.datastore.GetKey(name)
|
|
|
|
if err != nil {
|
|
|
|
return false, &ResponseCache{}
|
|
|
|
}
|
|
|
|
|
|
|
|
rc := &ResponseCache{}
|
|
|
|
err = json.Unmarshal([]byte(data.(string)), &rc)
|
|
|
|
if err != nil {
|
2021-07-24 17:46:22 +02:00
|
|
|
log.Println("Response-cache:", "JSON docode:", err)
|
|
|
|
return false, &ResponseCache{}
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return true, rc
|
|
|
|
}
|