github.com/zooyer/miskit@v1.0.71/imdb/driver.go (about) 1 package imdb 2 3 import ( 4 "context" 5 "fmt" 6 "sync" 7 ) 8 9 var ( 10 drivers = make(map[string]Driver) 11 mutex sync.Mutex 12 ) 13 14 type Conn interface { 15 Get(ctx context.Context, key string) (value string, err error) 16 Set(ctx context.Context, key, value string) (err error) 17 SetEx(ctx context.Context, key, value string, seconds int64) (err error) 18 Del(ctx context.Context, key string) (err error) 19 TTL(ctx context.Context, key string) (seconds int64, err error) 20 } 21 22 type Driver interface { 23 Open(args string) (conn Conn, err error) 24 } 25 26 func Register(name string, driver Driver) { 27 mutex.Lock() 28 defer mutex.Unlock() 29 30 if driver == nil { 31 panic("imdb: Register driver is nil") 32 } 33 34 if _, dup := drivers[name]; dup { 35 panic("imdb: Register called twice for driver " + name) 36 } 37 38 drivers[name] = driver 39 } 40 41 func Open(dialect string, args string) (conn Conn, err error) { 42 driver, exists := drivers[dialect] 43 if !exists || driver == nil { 44 return nil, fmt.Errorf("imdb: unknown driver %q (forgotten import?)", dialect) 45 } 46 47 return driver.Open(args) 48 }