From 61563b35d86341f06dbf0b987968e631131f512a Mon Sep 17 00:00:00 2001 From: rjbasitali Date: Tue, 7 Dec 2021 17:34:49 +0500 Subject: [PATCH] init --- cache.go | 7 +++++++ errors.go | 7 +++++++ get.go | 13 +++++++++++++ go.mod | 3 +++ my_cache.go | 16 ++++++++++++++++ remove.go | 15 +++++++++++++++ set.go | 11 +++++++++++ value.go | 13 +++++++++++++ 8 files changed, 85 insertions(+) create mode 100644 cache.go create mode 100644 errors.go create mode 100644 get.go create mode 100644 go.mod create mode 100644 my_cache.go create mode 100644 remove.go create mode 100644 set.go create mode 100644 value.go diff --git a/cache.go b/cache.go new file mode 100644 index 0000000..97f31c2 --- /dev/null +++ b/cache.go @@ -0,0 +1,7 @@ +package gocache + +type Cache interface { + Get(key string) (interface{}, error) + Set(key string, data interface{}) error + Remove(key string) error +} diff --git a/errors.go b/errors.go new file mode 100644 index 0000000..c29bb5e --- /dev/null +++ b/errors.go @@ -0,0 +1,7 @@ +package gocache + +import "errors" + +var ( + ErrKeyNotFound = errors.New("Key not found") +) diff --git a/get.go b/get.go new file mode 100644 index 0000000..ca1d8ef --- /dev/null +++ b/get.go @@ -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 +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..db316b9 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/rjbasitali/go-cache + +go 1.16 diff --git a/my_cache.go b/my_cache.go new file mode 100644 index 0000000..89348d1 --- /dev/null +++ b/my_cache.go @@ -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), + } +} diff --git a/remove.go b/remove.go new file mode 100644 index 0000000..384684e --- /dev/null +++ b/remove.go @@ -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 +} diff --git a/set.go b/set.go new file mode 100644 index 0000000..eceff2a --- /dev/null +++ b/set.go @@ -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 +} diff --git a/value.go b/value.go new file mode 100644 index 0000000..4aaad8f --- /dev/null +++ b/value.go @@ -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, + } +}