diff --git a/cache_memory.go b/cache_memory.go index 2f233cd..9489786 100644 --- a/cache_memory.go +++ b/cache_memory.go @@ -2,6 +2,7 @@ package main import ( "github.com/minotar/minecraft" + "time" ) const ( @@ -65,6 +66,17 @@ func (c *CacheMemory) pull(username string) minecraft.Skin { return c.Skins[username] } +// Removes the username from the cache +func (c *CacheMemory) remove(username string) { + index := indexOf(username, c.Usernames) + if index == -1 { + return + } + + key := c.Usernames[index] + delete(c.Skins, key) +} + // Adds the skin to the cache, remove the oldest, expired skin if the cache // list is full. func (c *CacheMemory) add(username string, skin minecraft.Skin) { @@ -77,6 +89,11 @@ func (c *CacheMemory) add(username string, skin minecraft.Skin) { } c.Skins[username] = skin + + // After the expiration time, remove the item from the cache. + time.AfterFunc(time.Duration(config.Server.Ttl)*time.Second, func() { + c.remove(username) + }) } // The byte size of the cache. Fairly rough... don't really want to venture diff --git a/cache_redis.go b/cache_redis.go index 6916605..e33556e 100644 --- a/cache_redis.go +++ b/cache_redis.go @@ -113,7 +113,7 @@ func (c *CacheRedis) add(username string, skin minecraft.Skin) { _ = png.Encode(skinBuf, skin.Image) // read into err so that it's set for the defer - err = client.Cmd("SETEX", "skins:"+username, config.Redis.Ttl, skinBuf.Bytes()).Err + err = client.Cmd("SETEX", "skins:"+username, strconv.Itoa(config.Server.Ttl), skinBuf.Bytes()).Err } func (c *CacheRedis) remove(username string) { diff --git a/config.example.gcfg b/config.example.gcfg index 044e641..71a0179 100644 --- a/config.example.gcfg +++ b/config.example.gcfg @@ -7,12 +7,13 @@ cache = memory # Whether to store statistics about API usage. This requires a # redis connection if true (fill the config below). statisticsEnabled = false +# The duration, in seconds we should store item in our cache. Default: 48 hrs +ttl = 172800 [redis] # If you're using Redis caching, you should fill this section out. # Otherwise, don't worry about it address = 127.0.0.1:6379 -ttl = 172800 # "auth" is optional, it can be left blank if you don't need authentication. auth = # We'll place this before skin caches in Redis to prevent conflicts. diff --git a/configuration.go b/configuration.go index 50741b7..41697dd 100644 --- a/configuration.go +++ b/configuration.go @@ -19,11 +19,11 @@ type Configuration struct { Address string Cache string StatisticsEnabled bool + Ttl int } Redis struct { Address string - Ttl string Auth string Prefix string PoolSize int