Switch to Fiber cache (closes #63)

This commit is contained in:
video-prize-ranch 2022-10-14 20:27:37 -04:00
parent 1f1d930072
commit 9d65fa95b4
No known key found for this signature in database
3 changed files with 9 additions and 38 deletions

View File

@ -3,11 +3,6 @@ PORT=3000
FIBER_PREFORK=false
IMGUR_CLIENT_ID=546c25a59c58ad7
# Create IMAGE_CACHE_DIR before enabling image caching
IMAGE_CACHE=false
IMAGE_CACHE_DIR=/var/cache/rimgo
IMAGE_CACHE_CLEANUP_INTERVAL=24h
# Instance privacy
# For more information, see https://codeberg.org/librarian/librarian/wiki/Instance-privacy
# Required to be on the instance list.

22
main.go
View File

@ -3,10 +3,7 @@ package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
"codeberg.org/video-prize-ranch/rimgo/pages"
@ -15,6 +12,7 @@ import (
"codeberg.org/video-prize-ranch/rimgo/views"
"github.com/aymerick/raymond"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cache"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/handlebars"
@ -29,18 +27,6 @@ func main() {
}
utils.LoadConfig()
if utils.Config.ImageCache {
go func() {
for range time.Tick(utils.Config.CleanupInterval) {
log.Println("Cache cleaned")
files, _ := filepath.Glob(filepath.Join(utils.Config.CacheDir, "*"))
for _, file := range files {
os.RemoveAll(file)
}
}
}()
}
engine := handlebars.NewFileSystem(http.FS(views.GetFiles()), ".hbs")
engine.AddFunc("noteq", func(a interface{}, b interface{}, options *raymond.Options) interface{} {
@ -86,6 +72,12 @@ func main() {
},
Root: http.FS(static.GetFiles()),
}))
app.Use(cache.New(cache.Config{
Expiration: 30 * time.Minute,
MaxBytes: 25000000,
CacheControl: true,
StoreResponseHeaders: true,
}))
app.Get("/robots.txt", func(c *fiber.Ctx) error {
file, _ := static.GetFiles().ReadFile("robots.txt")

View File

@ -3,7 +3,6 @@ package pages
import (
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
"strings"
@ -83,20 +82,5 @@ func handleMedia(c *fiber.Ctx, url string) error {
c.Set("Content-Range", res.Header.Get("Content-Range"))
}
if strings.HasPrefix(res.Header.Get("Content-Type"), "image/") && utils.Config.ImageCache && res.StatusCode == 200 {
data, err := io.ReadAll(res.Body)
if err != nil {
return err
}
err = os.WriteFile(utils.Config.CacheDir + "/" + optionsHash, data, 0644)
if err != nil {
return err
}
_, err = c.Write(data)
return err
} else {
return c.SendStream(res.Body)
}
}