wakapi/routes/api/avatar.go

51 lines
1.1 KiB
Go
Raw Normal View History

package api
import (
"codeberg.org/Codeberg/avatars"
2023-03-03 22:40:50 +03:00
"github.com/go-chi/chi/v5"
2022-02-17 12:34:33 +03:00
lru "github.com/hashicorp/golang-lru"
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/utils"
"net/http"
"time"
)
type AvatarHandler struct {
config *conf.Config
2022-02-17 12:34:33 +03:00
cache *lru.Cache
}
func NewAvatarHandler() *AvatarHandler {
2022-02-17 12:34:33 +03:00
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,
}
}
2023-03-03 22:40:50 +03:00
func (h *AvatarHandler) RegisterRoutes(router chi.Router) {
router.Get("/avatar/{hash}.svg", h.Get)
}
func (h *AvatarHandler) Get(w http.ResponseWriter, r *http.Request) {
2023-03-03 22:40:50 +03:00
hash := chi.URLParam(r, "hash")
if utils.IsNoCache(r, 1*time.Hour) {
h.cache.Remove(hash)
}
2022-02-17 12:34:33 +03:00
if !h.cache.Contains(hash) {
2022-11-27 00:26:03 +03:00
h.cache.Add(hash, avatars.MakeAvatar(hash))
}
2022-02-17 12:34:33 +03:00
data, _ := h.cache.Get(hash)
w.Header().Set("Content-Type", "image/svg+xml")
2022-02-17 12:34:33 +03:00
w.Header().Set("Cache-Control", "max-age=2592000")
w.WriteHeader(http.StatusOK)
2022-02-17 12:34:33 +03:00
w.Write([]byte(data.(string)))
}