mirror of https://github.com/rjbasitali/go-cache
commit
61563b35d8
|
|
@ -0,0 +1,7 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
type Cache interface {
|
||||||
|
Get(key string) (interface{}, error)
|
||||||
|
Set(key string, data interface{}) error
|
||||||
|
Remove(key string) error
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrKeyNotFound = errors.New("Key not found")
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
func (cache *myCache) Get(key string) (interface{}, error) {
|
||||||
|
cache.mutex.Lock()
|
||||||
|
defer cache.mutex.Unlock()
|
||||||
|
|
||||||
|
item, exists := cache.items[key]
|
||||||
|
if !exists {
|
||||||
|
return nil, ErrKeyNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type myCache struct {
|
||||||
|
mutex sync.Mutex
|
||||||
|
items map[string]*value
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCache() Cache {
|
||||||
|
return &myCache{
|
||||||
|
items: make(map[string]*value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
func (cache *myCache) Remove(key string) error {
|
||||||
|
cache.mutex.Lock()
|
||||||
|
defer cache.mutex.Unlock()
|
||||||
|
|
||||||
|
_, exists := cache.items[key]
|
||||||
|
if !exists {
|
||||||
|
return ErrKeyNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(cache.items, key)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
package gocache
|
||||||
|
|
||||||
|
func (cache *myCache) Set(key string, data interface{}) error {
|
||||||
|
cache.mutex.Lock()
|
||||||
|
defer cache.mutex.Unlock()
|
||||||
|
|
||||||
|
value := newValue(key, data)
|
||||||
|
cache.items[key] = value
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue