-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
53 lines (46 loc) · 1.22 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package nscache
import (
"errors"
"net/url"
"strings"
"sync"
"github.com/no-src/log"
)
var (
drivers = make(map[string]CacheFactoryFunc)
mu sync.RWMutex
)
var (
errCacheDriverFactoryIsNil = errors.New("the cache driver factory can't be nil")
errUnsupportedCacheDriver = errors.New("unsupported cache driver")
errInvalidCacheDriverName = errors.New("invalid cache driver name")
)
// CacheFactoryFunc the cache driver factory function
type CacheFactoryFunc func(conn *url.URL) (NSCache, error)
// Register register a new cache driver
func Register(name string, factory CacheFactoryFunc) (overwritten bool) {
if factory == nil {
panic(errCacheDriverFactoryIsNil)
}
name = strings.ToLower(name)
checked, checkedName := checkDriverName(name)
if !checked || checkedName != name {
panic(errInvalidCacheDriverName)
}
mu.Lock()
if _, exist := drivers[name]; exist {
log.Debug("the cache driver [%s] already existed", name)
overwritten = true
}
drivers[name] = factory
mu.Unlock()
log.Debug("the cache driver [%s] is registered", name)
return overwritten
}
func checkDriverName(name string) (checked bool, checkedName string) {
u, err := url.Parse(name + ":")
if err != nil {
return
}
return true, u.Scheme
}