Files
lambda/cache.go

102 lines
1.9 KiB
Go
Raw Normal View History

2026-01-29 21:35:36 +00:00
package main
// This file caches images in memory so we are not loading them from disk every time we need them
// It also does the same for images that need to be grabbed from HTTP.
import (
"github.com/diamondburned/gotk4/pkg/gdk/v4"
"github.com/diamondburned/gotk4/pkg/gtk/v4"
"crypto/sha256"
"fmt"
"net/http"
"io"
"os"
)
// global or app-level map/cache
var textureCache = make(map[string]gdk.Paintabler)
func getTexture(path string) gdk.Paintabler {
if tex, exists := textureCache[path]; exists {
return tex
}
tex, err := gdk.NewTextureFromFilename(path) // load once
if err != nil {
panic(err)
}
textureCache[path] = tex
return tex
}
func newPictureFromPath(path string) *gtk.Picture {
tex := getTexture(path)
img := gtk.NewPictureForPaintable(tex)
return img
}
func newImageFromPath(path string) *gtk.Image {
tex := getTexture(path)
img := gtk.NewImageFromPaintable(tex)
return img
}
func newPictureFromWeb(url string) *gtk.Picture {
// step 1: get a sha256 sum of the URL
sum := fmt.Sprintf("%x", sha256.Sum256([]byte(url)))
p, ok := textureCache[sum]
if ok {
return gtk.NewPictureForPaintable(p)
}
// step 2: download it
resp, err := http.Get(url)
if err != nil {
return nil
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil
}
// step 3: save it
err = os.WriteFile(sum, b, 0644)
if err != nil {
return nil
}
return newPictureFromPath(sum)
}
func newImageFromWeb(url string) *gtk.Image {
// step 1: get a sha256 sum of the URL
sum := fmt.Sprintf("%x", sha256.Sum256([]byte(url)))
p, ok := textureCache[sum]
if ok {
return gtk.NewImageFromPaintable(p)
}
// step 2: download it
resp, err := http.Get(url)
if err != nil {
return nil
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil
}
// step 3: save it
err = os.WriteFile(sum, b, 0644)
if err != nil {
return nil
}
return newImageFromPath(sum)
}