// ___ ____ ___ ___ // \ \ / / | _ | __| \ \ / / || | __ || || _ | // \ \/ / |___ | |__ \ \/ / || |___ || ||___| // \ / | _ | _ | \ / || __ | || ||\\ // \/ |___ |___ | \/ || ____| || || \\ // // Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License // Repo: https://git.pbiernat.dev/golang/vegvisir package cache import ( "encoding/json" "log" ) // Headers type type Headers map[string]string // ResponseCache struct type ResponseCache struct { URL string Body string Headers Headers } // ResponseCacheManager class type ResponseCacheManager struct { datastore Datastore prefix string ttl int } // NewResponseCacheManager function func NewResponseCacheManager(datastore Datastore, ttl int) ResponseCacheManager { return ResponseCacheManager{ datastore: datastore, prefix: "response_", ttl: ttl, } } // Save function 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 { log.Println("Response-cache:", err, name) return false } return true } // Load function 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 }