From 59ea5da52140af7003def9029d015f23c49da11a Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Wed, 7 Nov 2018 22:07:33 -0500 Subject: [PATCH] Add login and post cache helpers --- cache.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 cache.go diff --git a/cache.go b/cache.go new file mode 100644 index 0000000..4fb8d0c --- /dev/null +++ b/cache.go @@ -0,0 +1,59 @@ +package writefreely + +import ( + "sync" + "time" +) + +const ( + postsCacheTime = 4 * time.Second +) + +type ( + postsCacheItem struct { + Expire time.Time + Posts *[]PublicPost + ready chan struct{} + } + + AuthCache struct { + Alias, Pass, Token string + BadPasses map[string]bool + + expire time.Time + } +) + +var ( + userPostsCache = struct { + sync.RWMutex + users map[int64]postsCacheItem + }{ + users: map[int64]postsCacheItem{}, + } +) + +func CachePosts(userID int64, p *[]PublicPost) { + close(userPostsCache.users[userID].ready) + userPostsCache.Lock() + userPostsCache.users[userID] = postsCacheItem{ + Expire: time.Now().Add(postsCacheTime), + Posts: p, + } + userPostsCache.Unlock() +} + +func GetPostsCache(userID int64) *[]PublicPost { + userPostsCache.RLock() + pci, ok := userPostsCache.users[userID] + userPostsCache.RUnlock() + if !ok { + return nil + } + + if pci.Expire.Before(time.Now()) { + // Cache is expired + return nil + } + return pci.Posts +}