vegvisir/pkg/cache/response.go

82 lines
1.8 KiB
Go
Raw 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"
)
2021-07-25 20:13:03 +02:00
type Headers map[string]string
type ResponseCache struct {
2021-07-25 20:13:03 +02:00
URL string
Body string
Headers Headers
}
type ResponseCacheManager struct {
datastore CacheDatastore
prefix string
ttl int
}
func NewResponseCacheManager(datastore CacheDatastore, ttl int) ResponseCacheManager {
return ResponseCacheManager{
datastore: datastore,
prefix: "response_",
ttl: ttl,
}
}
func (rm *ResponseCacheManager) Save(name string, r ResponseCache) bool {
if !rm.datastore.IsConnected() {
log.Println("Response-cache:", "Not connected to server")
return false
}
data, err := json.Marshal(r)
if err != nil {
log.Println("Response-cache", "JSON encode:", err)
return false
}
name = rm.prefix + name
err = rm.datastore.SetKey(name, string(data), rm.ttl)
if err != nil {
2021-07-25 01:44:50 +02:00
log.Println("Response-cache:", err, name)
return false
}
return true
}
func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) {
if !rm.datastore.IsConnected() {
log.Println("Response-cache:", "Not connected to server")
return false, &ResponseCache{}
}
name = rm.prefix + name
data, err := rm.datastore.GetKey(name)
if err != nil {
return false, &ResponseCache{}
}
rc := &ResponseCache{}
err = json.Unmarshal([]byte(data.(string)), &rc)
if err != nil {
log.Println("Response-cache:", "JSON docode:", err)
return false, &ResponseCache{}
}
return true, rc
}