gowiki/cache.go
2018-02-07 21:41:54 +01:00

49 lines
815 B
Go

package main
import (
"sync"
"time"
)
type CachedArticle struct {
Article *Article
CacheTime time.Time
}
type IndexCache struct {
sync.RWMutex
Cache map[string]*CachedArticle
}
func NewIndexCache() *IndexCache {
return &IndexCache{Cache: make(map[string]*CachedArticle)}
}
func (ic IndexCache) Add(title string, a *Article) {
now := time.Now()
ic.Lock()
defer ic.Unlock()
c, ok := ic.Cache[title]
if ok && now.After(c.CacheTime) {
c.Article = a
c.CacheTime = now
ic.Cache[title] = c
return
}
ic.Cache[title] = &CachedArticle{a, now}
}
func (ic IndexCache) Get(title string) *Article {
ic.RLock()
defer ic.RUnlock()
if a, ok := ic.Cache[title]; ok {
return a.Article
}
return nil
}
func (ic *IndexCache) Delete(title string) {
ic.Lock()
delete(ic.Cache, title)
ic.Unlock()
}