2017-06-22 17:06:39 +03:00
|
|
|
package rest
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/md5"
|
2017-06-23 10:22:49 +03:00
|
|
|
"encoding/base64"
|
2017-06-22 17:06:39 +03:00
|
|
|
"github.com/bradfitz/gomemcache/memcache"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Memcached connection settings
|
|
|
|
type MC struct {
|
|
|
|
Enabled bool `json:"enabled"`
|
|
|
|
Hosts []string `json:"hosts"`
|
|
|
|
Prefix string `json:"prefix"`
|
|
|
|
Client *memcache.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
// InitConnection to memcached cluster
|
|
|
|
func (mc MC) InitConnection() *memcache.Client {
|
|
|
|
client := memcache.New(mc.Hosts...)
|
|
|
|
return client
|
|
|
|
}
|
|
|
|
|
|
|
|
// StoreToCache save data to memecache
|
|
|
|
func (mc MC) StoreToCache(key string, data []byte) error {
|
|
|
|
prefixed_key := strings.Join([]string{mc.Prefix, key}, "_")
|
|
|
|
|
|
|
|
var item memcache.Item
|
|
|
|
// item.Key = hashKey(prefixed_key)
|
2017-06-23 10:22:49 +03:00
|
|
|
item.Key = hashKey(prefixed_key)
|
2017-06-22 17:06:39 +03:00
|
|
|
item.Value = data
|
|
|
|
|
|
|
|
// store
|
|
|
|
err := mc.Client.Set(&item)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-06-23 10:22:49 +03:00
|
|
|
// GetFromCache get node data from memcache
|
2017-06-22 17:06:39 +03:00
|
|
|
func (mc MC) GetFromCache(key string) ([]byte, error) {
|
|
|
|
var data *memcache.Item
|
|
|
|
prefixed_key := strings.Join([]string{mc.Prefix, key}, "_")
|
|
|
|
|
2017-06-23 10:22:49 +03:00
|
|
|
data, err := mc.Client.Get(hashKey(prefixed_key))
|
2017-06-22 17:06:39 +03:00
|
|
|
if err != nil {
|
|
|
|
return []byte(""), err
|
|
|
|
}
|
|
|
|
|
|
|
|
return data.Value, err
|
|
|
|
}
|
|
|
|
|
2017-06-23 10:22:49 +03:00
|
|
|
// DeleteFromCache delete key from memcache
|
|
|
|
func (mc MC) DeleteFromCache(key string) error {
|
|
|
|
prefixed_key := strings.Join([]string{mc.Prefix, key}, "_")
|
|
|
|
|
|
|
|
err := mc.Client.Delete(hashKey(prefixed_key))
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// hashKey return base64 encoded md5sum of prefixed_key
|
2017-06-22 17:06:39 +03:00
|
|
|
func hashKey(key string) string {
|
|
|
|
h := md5.New()
|
|
|
|
sum := h.Sum([]byte(key))
|
|
|
|
|
2017-06-23 10:22:49 +03:00
|
|
|
b64 := base64.StdEncoding.EncodeToString(sum)
|
|
|
|
|
|
|
|
return b64
|
2017-06-22 17:06:39 +03:00
|
|
|
}
|