105 lines
1.8 KiB
Go
105 lines
1.8 KiB
Go
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"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Type string
|
|
|
|
const (
|
|
TypeMemcache Type = "memcache"
|
|
TypeRedis Type = "redis"
|
|
TypeMemory Type = "memory"
|
|
TypeLru Type = "lru"
|
|
)
|
|
|
|
var (
|
|
ErrInvalidDriver = errors.New("invalid driver")
|
|
)
|
|
|
|
func init() {
|
|
var err error
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
type Driver interface {
|
|
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)
|
|
Del(key string) error
|
|
}
|
|
|
|
type (
|
|
Marshaller func(val any) ([]byte, error)
|
|
Unmarshaler func(b []byte, dest any) error
|
|
)
|
|
|
|
func New(uri string) (Driver, error) {
|
|
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)
|
|
|
|
return redis.New(settings)
|
|
case TypeMemcache:
|
|
var options memcache.Options
|
|
|
|
if err = decodeQuery(query, &options); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
options.Servers = strings.Split(u.Host, ",")
|
|
|
|
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
|
|
}
|