Implement caching

parent a56542f8
package main
type CacheBackend interface {
Set(namespace string, key string, value interface{}) error
Get(namespace string, key string, value interface{}) error
}
\ No newline at end of file
package main
import (
"encoding/json"
"fmt"
"time"
)
import "github.com/patrickmn/go-cache"
type MemoryCache struct {
backend *cache.Cache
}
func (m MemoryCache) Set(namespace string, key string, value interface{}) error {
var err error
var serialized []byte
if serialized, err = json.Marshal(&value); err != nil {
return err
}
m.backend.SetDefault(fmt.Sprintf("%s:%s", namespace, key), serialized)
return nil
}
func (m MemoryCache) Get(namespace string, key string, value interface{}) error {
var err error
var serialized []byte
if raw, found := m.backend.Get(fmt.Sprintf("%s:%s", namespace, key)); found {
serialized = raw.([]byte)
}
if err = json.Unmarshal(serialized, &value); err != nil {
return err
}
return nil
}
func NewMemoryCache(expirationTime time.Duration) CacheBackend {
return MemoryCache{
backend: cache.New(expirationTime, expirationTime*2),
}
}
\ No newline at end of file
......@@ -4,5 +4,6 @@ go 1.12
require (
git.kuschku.de/justjanne/bahn-api v0.0.0-20190503215445-3da40decb307
github.com/patrickmn/go-cache v2.1.0+incompatible
golang.org/x/text v0.3.2 // indirect
)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment