cacheinterface/cache.go

105 lines
1.8 KiB
Go
Raw Permalink Normal View History

2019-10-02 04:10:27 +00:00
package cache
import (
"errors"
"meow.tf/go/cacheinterface/v2/driver/lru"
"meow.tf/go/cacheinterface/v2/driver/memcache"
"meow.tf/go/cacheinterface/v2/driver/memory"
"meow.tf/go/cacheinterface/v2/driver/redis"
"net"
2019-10-02 04:10:27 +00:00
"net/url"
"strings"
"time"
)
type Type string
2019-10-02 04:10:27 +00:00
const (
TypeMemcache Type = "memcache"
TypeRedis Type = "redis"
TypeMemory Type = "memory"
TypeLru Type = "lru"
2019-10-02 04:10:27 +00:00
)
var (
ErrInvalidDriver = errors.New("invalid driver")
)
func init() {
var err error
if err != nil {
panic(err)
}
}
type Driver interface {
2019-10-02 04:10:27 +00:00
Has(key string) bool
Get(key string, dst any) error
GetBytes(key string) ([]byte, error)
Set(key string, val any, ttl time.Duration) (err error)
2019-10-02 04:10:27 +00:00
Del(key string) error
}
type (
Marshaller func(val any) ([]byte, error)
Unmarshaler func(b []byte, dest any) error
)
func New(uri string) (Driver, error) {
2019-10-02 04:10:27 +00:00
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
query := u.Query()
switch Type(u.Scheme) {
case TypeRedis:
port := u.Port()
if port == "" {
port = "6379"
}
var settings redis.Options
if err = decodeQuery(query, &settings); err != nil {
return nil, err
}
settings.Address = net.JoinHostPort(u.Hostname(), port)
2019-10-05 20:56:24 +00:00
return redis.New(settings)
case TypeMemcache:
var options memcache.Options
2019-10-05 20:56:24 +00:00
if err = decodeQuery(query, &options); err != nil {
2019-10-05 20:56:24 +00:00
return nil, err
}
options.Servers = strings.Split(u.Host, ",")
2019-10-02 04:10:27 +00:00
return memcache.New(options)
case TypeMemory:
var options memory.Options
if err = decodeQuery(query, &options); err != nil {
return nil, err
}
return memory.New(options)
case TypeLru:
var options lru.Options
if err = decodeQuery(query, &options); err != nil {
return nil, err
}
return lru.New(options)
}
return nil, ErrInvalidDriver
}