64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
|
package cache
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"github.com/bradfitz/gomemcache/memcache"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type MemcacheSettings struct {
|
||
|
Servers []string
|
||
|
}
|
||
|
|
||
|
type MemcacheCache struct {
|
||
|
backend *memcache.Client
|
||
|
}
|
||
|
|
||
|
func NewMemcacheCache(s MemcacheSettings) (CacheInterface, error) {
|
||
|
c := memcache.New(s.Servers...)
|
||
|
|
||
|
return &MemcacheCache{
|
||
|
backend: c,
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func (mc *MemcacheCache) Has(key string) bool {
|
||
|
_, err := mc.backend.Get(key)
|
||
|
|
||
|
return err != nil
|
||
|
}
|
||
|
|
||
|
func (mc *MemcacheCache) Get(key string) ([]byte, error) {
|
||
|
item, err := mc.backend.Get(key)
|
||
|
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return item.Value, nil
|
||
|
}
|
||
|
|
||
|
func (mc *MemcacheCache) Set(key string, val interface{}, ttl time.Duration) error {
|
||
|
var v []byte
|
||
|
|
||
|
if b, ok := val.([]byte); ok {
|
||
|
v = b
|
||
|
} else if s, ok := val.(string); ok {
|
||
|
b = []byte(s)
|
||
|
} else {
|
||
|
b, err := json.Marshal(val)
|
||
|
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
v = b
|
||
|
}
|
||
|
|
||
|
return mc.backend.Set(&memcache.Item{Key: key, Value: v, Expiration: int32(ttl.Seconds())})
|
||
|
}
|
||
|
|
||
|
func (mc *MemcacheCache) Del(key string) error {
|
||
|
return mc.backend.Delete(key)
|
||
|
}
|