--wip-- [skip ci]

This commit is contained in:
schreifuchs committed 2026-09-14 20:24:56 +02:00
1 parent 72bc974aa6
commit bca93f6c6c
12 files changed
+256 -54

No files matched your search

+4 -4
View File
@@ -20,16 +20,16 @@ type Set struct {
}
func (s *Service) GetGallerySet(ctx context.Context) (gallerySet Set, err error) {
gallerySet.SM, err = s.GetGallery(ctx, 50)
gallerySet.SM, err = s.getGallery(ctx, 50)
if err != nil {
return
}
gallerySet.LG, err = s.GetGallery(ctx, 80)
gallerySet.LG, err = s.getGallery(ctx, 80)
if err != nil {
return
}
gallerySet.XLG, err = s.GetGallery(ctx, 120)
gallerySet.XLG, err = s.getGallery(ctx, 120)
if err != nil {
return
}
@@ -37,7 +37,7 @@ func (s *Service) GetGallerySet(ctx context.Context) (gallerySet Set, err error)
return
}
func (s *Service) GetGallery(ctx context.Context, width int) (gallery Gallery, err error) {
func (s *Service) getGallery(ctx context.Context, width int) (gallery Gallery, err error) {
imgs, err := s.GetImages(ctx)
if err != nil {
return
+30
View File
@@ -12,6 +12,7 @@ import (
"time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
"github.com/valkey-io/valkey-go"
)
@@ -124,3 +125,32 @@ func (s *Service) GetImages(ctx context.Context) (images []Image, err error) {
err = s.cache.Do(ctx, s.cache.B().Get().Key(imagesKey).Build()).DecodeJSON(&images)
return
}
func (s *Service) GetPrevAndNext(ctx context.Context, uid string) (previous *Image, next *Image, err error) {
imgs, err := s.GetImages(ctx)
if err != nil {
return
}
for i := range imgs {
if imgs[i].UID != uid {
continue
}
if i-1 >= 0 {
previous = &imgs[i-1]
}
if i+1 >= len(imgs) {
next = &imgs[i+1]
}
return
}
err = &rest.Error{
Type: rest.ErrorTypeNotFound,
Message: "could not find image with uid",
}
return
}
+18 -4
View File
@@ -5,6 +5,7 @@ import (
"log/slog"
"net/http"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
)
@@ -14,8 +15,8 @@ const preloadCount = 6
func (h *Handler) gallery(w http.ResponseWriter, r *http.Request) {
imgs, err := h.srv.GetGallerySet(r.Context())
if err != nil {
slog.Error("could not get images", "err", err)
w.WriteHeader(http.StatusInternalServerError)
slog.Error("could not get gallery set", "err", err)
rest.SendErr(w, err)
return
}
ctx := r.Context()
@@ -23,9 +24,22 @@ func (h *Handler) gallery(w http.ResponseWriter, r *http.Request) {
if i > preloadCount {
break
}
slog.Info("preloading images", "img", image.UID)
ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s" as="image" />`, image.URL()))
ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s?w=800" as="image" />`, image.URL()))
}
h.r.Render(ctx, w, r, pages.GallerySet(imgs))
}
func (h *Handler) image(w http.ResponseWriter, r *http.Request) {
uid := r.PathValue("image_uid")
slog.Debug("image from gallery", "uid", uid)
prev, next, err := h.srv.GetPrevAndNext(r.Context(), uid)
if err != nil {
slog.Error("could not get gallery", "err", err)
rest.SendErr(w, err)
return
}
h.r.Render(r.Context(), w, r, pages.GalleryImage(uid, next, prev))
}
+5 -1
View File
@@ -28,12 +28,16 @@ func New(renderer renderer, srv galleryService, cfg *config.Gallery) *Handler {
cfg: cfg,
}
mux.HandleFunc(fmt.Sprintf("GET /%s", url.PathEscape(cfg.Path)), h.gallery)
galleryPath := url.PathEscape(cfg.Path)
mux.HandleFunc(fmt.Sprintf("GET /%s/{image_uid}", galleryPath), h.image)
mux.HandleFunc(fmt.Sprintf("GET /%s", galleryPath), h.gallery)
return h
}
type galleryService interface {
GetGallerySet(ctx context.Context) (gallerySet gallery.Set, err error)
GetPrevAndNext(ctx context.Context, uid string) (previous *gallery.Image, next *gallery.Image, err error)
}
type renderer interface {
Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component)
+10 -11
View File
@@ -98,7 +98,7 @@ func (m *MockFS) ReadDir(path string) ([]os.FileInfo, error) {
if len(prefix) > 0 && prefix[len(prefix)-1] != '/' {
prefix += "/"
}
if len(p) > len(prefix) && p[:len(prefix)] == prefix {
// Ensure direct child (no more slashes)
rel := p[len(prefix):]
@@ -150,7 +150,7 @@ func TestCachedClient_Stat(t *testing.T) {
mockFS := NewMockFS()
mockFS.AddFile("/test.txt", []byte("hello"))
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// First call: Cache miss
info, err := c.Stat("/test.txt")
@@ -209,7 +209,7 @@ func TestCachedClient_Read(t *testing.T) {
content := []byte("hello world")
mockFS.AddFile("/read.txt", content)
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// First call: Miss
data, err := c.Read("/read.txt")
@@ -257,7 +257,7 @@ func TestCachedClient_ReadDir(t *testing.T) {
mockFS.AddFile("/dir/f1.txt", []byte("1"))
mockFS.AddFile("/dir/f2.txt", []byte("2"))
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// First call: Miss
infos, err := c.ReadDir("/dir")
@@ -303,7 +303,7 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
mockFS := NewMockFS()
mockFS.AddFile("/reval.txt", []byte("initial"))
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// Populate cache
_, _ = c.Stat("/reval.txt")
@@ -342,7 +342,7 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
// We can inspect redis directly or trust `Stat` returns cached value (which should be updated).
// Let's inspect redis to be sure.
// Or just call Stat again. It should be a cache HIT, but return NEW values.
// Reset stats to check hit
c.hits.Store(0)
c.misses.Store(0)
@@ -351,11 +351,11 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
if err != nil {
t.Fatalf("Stat failed: %v", err)
}
if info.Size() != int64(len("updated content")) {
t.Errorf("expected size %d, got %d", len("updated content"), info.Size())
}
// Should be a hit because revalidate updated the cache entry, so it exists and is valid.
if c.hits.Load() != 1 {
t.Errorf("expected 1 hit, got %d", c.hits.Load())
@@ -381,7 +381,7 @@ func TestCachedClient_RevalidateRead(t *testing.T) {
mockFS := NewMockFS()
mockFS.AddFile("/read_reval.txt", []byte("initial"))
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// Populate cache
_, _ = c.Read("/read_reval.txt")
@@ -431,7 +431,7 @@ func TestCachedClient_RevalidateReadDir(t *testing.T) {
mockFS.AddDir("/dir_reval")
mockFS.AddFile("/dir_reval/f1.txt", []byte("1"))
c := NewCachedClient(mockFS, client, time.Hour)
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
// Populate cache
_, err = c.ReadDir("/dir_reval")
@@ -461,4 +461,3 @@ func TestCachedClient_RevalidateReadDir(t *testing.T) {
t.Errorf("expected 1 hit, got %d", c.hits.Load())
}
}
+30 -2
View File
@@ -2,8 +2,10 @@ package templer
import (
"context"
"fmt"
"log/slog"
"net/http"
"net/url"
"strings"
)
@@ -25,12 +27,38 @@ func Middleware(next http.Handler) http.HandlerFunc {
}
}
// Path returns the current path without a leading slash
// Path returns the current path with a leading slash
func Path(ctx context.Context) string {
path, ok := ctx.Value(pathKey).(string)
if !ok {
slog.Error("could not extract request path from context")
return ""
}
return strings.TrimPrefix(path, "/")
return path
}
func RelativePath(ctx context.Context, relPath string) (path string, err error) {
baseStr := Path(ctx)
if baseStr != "" && !strings.HasSuffix(baseStr, "/") {
baseStr += "/"
}
base, err := url.Parse(baseStr)
if err != nil {
err = fmt.Errorf("could not parse base path: %w", err)
return
}
rel, err := url.Parse(relPath)
if err != nil {
err = fmt.Errorf("could not parse relative path: %w", err)
return
}
// Resolve the relative path against the base
path = base.ResolveReference(rel).Path
if strings.HasSuffix(path, "/") {
path = path[:len(path)-1]
}
return
}
+75
View File
@@ -0,0 +1,75 @@
package templer
import (
"context"
"testing"
)
func TestRelativePath(t *testing.T) {
tests := []struct {
name string // description of this test case
// Named input parameters for target function.
base string
relPath string
want string
wantErr bool
}{
// TODO: Add test cases.
{
name: "with no relative path stays the same",
base: "/foo/bar",
relPath: "",
want: "/foo/bar",
wantErr: false,
},
{
name: "with . relative path stays the same",
base: "/foo/bar",
relPath: ".",
want: "/foo/bar",
wantErr: false,
},
{
name: "with ./ relative path stays the same",
base: "/foo/bar",
relPath: "./",
want: "/foo/bar",
wantErr: false,
},
{
name: "with .. relative path goes one up",
base: "/foo/bar",
relPath: "..",
want: "/foo",
wantErr: false,
},
{
name: "with ../baz relative path replaces last element with baz",
base: "/foo/bar",
relPath: "../baz",
want: "/foo/baz",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.WithValue(t.Context(), pathKey, tt.base)
got, gotErr := RelativePath(ctx, tt.relPath)
if gotErr != nil {
if !tt.wantErr {
t.Errorf("RelativePath() failed: %v", gotErr)
}
return
}
if tt.wantErr {
t.Fatal("RelativePath() succeeded unexpectedly")
}
// TODO: update the condition below to compare got with tt.want.
if got != tt.want {
t.Errorf("RelativePath() = %v, want %v", got, tt.want)
}
})
}
}
+1 -2
View File
@@ -3,7 +3,6 @@ package server
import (
"fmt"
"net/http"
"path"
"time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/gallery"
@@ -78,7 +77,7 @@ func (s *Server) dynamicRoutes() (h http.Handler, err error) {
func() http.Handler {
mux := http.NewServeMux()
mux.Handle(path.Join("/"+s.cfg.Gallery.Path), restgallery.New(renderer, gallery.New(fs, s.cfg.Gallery, imageSrv, valkeyClient), s.cfg.Gallery))
mux.Handle("/"+s.cfg.Gallery.Path, restgallery.New(renderer, gallery.New(fs, s.cfg.Gallery, imageSrv, valkeyClient), s.cfg.Gallery))
mux.Handle("/", resthome.New(renderer, page.New(fs)))
return mux