add-license-1 v0.0.1
Basit Ali 2021-12-07 17:34:49 +05:00
commit 61563b35d8
8 changed files with 85 additions and 0 deletions

7
cache.go 100644
View File

@ -0,0 +1,7 @@
package gocache
type Cache interface {
Get(key string) (interface{}, error)
Set(key string, data interface{}) error
Remove(key string) error
}

7
errors.go 100644
View File

@ -0,0 +1,7 @@
package gocache
import "errors"
var (
ErrKeyNotFound = errors.New("Key not found")
)

13
get.go 100644
View File

@ -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
}

3
go.mod 100644
View File

@ -0,0 +1,3 @@
module github.com/rjbasitali/go-cache
go 1.16

16
my_cache.go 100644
View File

@ -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),
}
}

15
remove.go 100644
View File

@ -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
}

11
set.go 100644
View File

@ -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
}

13
value.go 100644
View File

@ -0,0 +1,13 @@
package gocache
type value struct {
key string
data interface{}
}
func newValue(key string, data interface{}) *value {
return &value{
key: key,
data: data,
}
}