diff options
Diffstat (limited to 'backend/cache')
| -rw-r--r-- | backend/cache/cache.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/backend/cache/cache.go b/backend/cache/cache.go new file mode 100644 index 0000000..bac7ea8 --- /dev/null +++ b/backend/cache/cache.go @@ -0,0 +1,44 @@ +package cache + +import ( + "sync" + + "github.com/jackyzha0/ctrl-v/db" +) + +type Cache struct { + m map[string]db.Paste + lock sync.RWMutex +} + +var C *Cache + +func init() { + C = &Cache{ + m: map[string]db.Paste{}, + } +} + +func (c *Cache) Get(hash string) (db.Paste, error) { + c.lock.RLock() + + // check if hash in cache + v, ok := c.m[hash] + c.lock.RUnlock() + + if ok { + return v, nil + } + + // if it doesnt, lookup from db + p, err := db.Lookup(hash) + c.add(p) + return p, err +} + +func (c *Cache) add(p db.Paste) { + c.lock.Lock() + defer c.lock.Unlock() + + c.m[p.Hash] = p +} |