Implement caching

parent a56542f8
package main
import (
"encoding/json"
"git.kuschku.de/justjanne/bahn-api"
"time"
)
import "github.com/patrickmn/go-cache"
type MemoryCache struct {
backend *cache.Cache
}
func (m MemoryCache) Set(key string, value interface{}) error {
var err error
var serialized []byte
if serialized, err = json.Marshal(&value); err != nil {
return err
}
m.backend.SetDefault(key, serialized)
return nil
}
func (m MemoryCache) Get(key string, value interface{}) error {
var err error
var serialized []byte
if raw, found := m.backend.Get(key); found {
serialized = raw.([]byte)
}
if err = json.Unmarshal(serialized, &value); err != nil {
return err
}
return nil
}
func NewMemoryCache(expirationTime time.Duration) bahn.CacheBackend {
return MemoryCache{
backend: cache.New(expirationTime, expirationTime*2),
}
}
\ No newline at end of file
......@@ -3,6 +3,6 @@ module git.kuschku.de/justjanne/bahn-proxy
go 1.12
require (
git.kuschku.de/justjanne/bahn-api v0.0.0-20190503215445-3da40decb307
golang.org/x/text v0.3.2 // indirect
git.kuschku.de/justjanne/bahn-api v0.0.0-20190504113537-452e8eed7129
github.com/patrickmn/go-cache v2.1.0+incompatible
)
......@@ -37,6 +37,9 @@ func main() {
HttpClient: &http.Client{
Timeout: time.Second * 10,
},
Caches: []bahn.CacheBackend{
NewMemoryCache(5 * time.Minute),
},
}
MaxResults := 20
......
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