mirror of
https://github.com/muety/wakapi.git
synced 2023-08-10 21:12:56 +03:00
chore: cache avatars in memory
This commit is contained in:
@ -3,16 +3,26 @@ package api
|
||||
import (
|
||||
"codeberg.org/Codeberg/avatars"
|
||||
"github.com/gorilla/mux"
|
||||
lru "github.com/hashicorp/golang-lru"
|
||||
conf "github.com/muety/wakapi/config"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type AvatarHandler struct {
|
||||
config *conf.Config
|
||||
cache *lru.Cache
|
||||
}
|
||||
|
||||
func NewAvatarHandler() *AvatarHandler {
|
||||
return &AvatarHandler{config: conf.Get()}
|
||||
cache, err := lru.New(1 * 1000 * 64) // assuming an avatar is 1 kb, allocate up to 64 mb of memory for avatars cache
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return &AvatarHandler{
|
||||
config: conf.Get(),
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AvatarHandler) RegisterRoutes(router *mux.Router) {
|
||||
@ -21,15 +31,15 @@ func (h *AvatarHandler) RegisterRoutes(router *mux.Router) {
|
||||
}
|
||||
|
||||
func (h *AvatarHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
hash := mux.Vars(r)["hash"]
|
||||
|
||||
if vars["hash"] == "" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte{})
|
||||
return
|
||||
if !h.cache.Contains(hash) {
|
||||
h.cache.Add(hash, avatars.MakeMaleAvatar(hash))
|
||||
}
|
||||
data, _ := h.cache.Get(hash)
|
||||
|
||||
w.Header().Set("Content-Type", "image/svg+xml")
|
||||
w.Header().Set("Cache-Control", "max-age=2592000")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(avatars.MakeMaleAvatar(vars["hash"])))
|
||||
w.Write([]byte(data.(string)))
|
||||
}
|
||||
|
Reference in New Issue
Block a user