3 Commits
Author SHA1 Message Date
schreifuchs 01b24f830f chore: better resource loading
/ publish (push) Successful in 9m23s
2026-03-08 01:05:57 +01:00
schreifuchs eab7eb3879 chore: better config
/ publish (push) Successful in 3m1s
2026-03-07 20:55:04 +01:00
schreifuchs fca1030e1a feat: limit image request
/ publish (push) Successful in 3m9s
2026-03-07 20:26:53 +01:00
16 changed files with 59 additions and 16 deletions
+8 -1
View File
@@ -60,6 +60,13 @@ func (s *Service) getImage(uid string) (file []byte, mimeType string, err error)
}
func (s *Service) GetImage(ctx context.Context, uid string, options Options) (img io.Reader, mimeType string, err error) {
if err = s.seph.Acquire(ctx, 1); err != nil {
err = fmt.Errorf("could not Acquire semaphore: %w", err)
return
}
defer s.seph.Release(1)
rawImage, mimeType, err := s.getImage(uid)
if err != nil {
return
@@ -83,7 +90,7 @@ func (s *Service) GetImage(ctx context.Context, uid string, options Options) (im
outBuff := bytes.NewBuffer(make([]byte, 0, 1024))
if options.Quality == 0 {
options.Quality = 80
options.Quality = s.cfg.Quality
}
err = jpeg.Encode(outBuff, decImage, &jpeg.Options{Quality: options.Quality})
+7 -1
View File
@@ -3,7 +3,9 @@ package images
import (
"os"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
"github.com/valkey-io/valkey-go"
"golang.org/x/sync/semaphore"
)
type Options struct {
@@ -15,12 +17,16 @@ type Options struct {
type Service struct {
fs fileSystem
cache valkey.Client
seph *semaphore.Weighted
cfg *config.ImageConfig
}
func New(fs fileSystem, cache valkey.Client) *Service {
func New(fs fileSystem, cfg *config.ImageConfig, cache valkey.Client) *Service {
return &Service{
fs: fs,
cache: cache,
seph: semaphore.NewWeighted(cfg.Concurency),
cfg: cfg,
}
}
+3
View File
@@ -56,6 +56,9 @@ func imageMiddleware(page PageHeader) func(w io.Writer, node ast.Node, entering
img.Attribute = &ast.Attribute{Attrs: map[string][]byte{
"srcset": []byte(images.SourceSet(src)),
"fetchpriority": []byte("low"),
"loading": []byte("lazy"),
"class": []byte("min-h-48"),
"src": []byte(src),
}}
// // img.Attrs["srcset"] =
-3
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"log/slog"
"regexp"
"strings"
@@ -57,8 +56,6 @@ func (s *Service) getPageHeaders(ctx context.Context, uid string) (page PageHead
}
}
slog.Debug("loaded page infos", "cover", coverImage, "content", contentMD)
page.md, err = s.fs.Read(contentMD.Path())
if err != nil {
return
+1 -1
View File
@@ -65,7 +65,7 @@ func PathForLang(ctx context.Context, lang string, pp ...string) string {
}
}
return path.Join(append([]string{lang}, pp...)...)
return "/" + path.Join(append([]string{lang}, pp...)...)
}
func (s *Service) SupportedLanguages() (languages []string) {
+10
View File
@@ -0,0 +1,10 @@
package config
func Default() Cfg {
return Cfg{
Image: &ImageConfig{
Concurency: 10,
Quality: 80,
},
}
}
+7
View File
@@ -9,6 +9,7 @@ import (
type Cfg struct {
FileSystem *WebdavConfig `env:", prefix=FILESYSTEM_"`
Cache *ValkeyConfig `env:", prefix=CACHE_"`
Image *ImageConfig `env:", prefix=IMAGE_"`
}
type WebdavConfig struct {
@@ -30,7 +31,13 @@ type ValkeyConfig struct {
InitAddress []string `env:"ADDRESS"`
}
type ImageConfig struct {
Concurency int64 `env:"CONCURENCY"`
Quality int `env:"QUALITY"`
}
func Read(ctx context.Context) (cfg Cfg, err error) {
cfg = Default()
err = envconfig.ProcessWith(ctx, &envconfig.Config{
Target: &cfg,
+1 -1
View File
@@ -50,7 +50,7 @@ func (s *Server) registerOther() (h http.Handler) {
}
_ = resthome.New(mux, page.New(fs))
_ = restimage.New(mux, images.New(fs, valkeyClient))
_ = restimage.New(mux, images.New(fs, s.cfg.Image, valkeyClient))
mux.Handle("/", http.FileServer(http.FS(web.GetStaticFS())))
+2 -1
View File
@@ -6,7 +6,7 @@
"scripts": {
"build:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --minify",
"watch:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --watch",
"build:js": "cp node_modules/htmx.org/dist/htmx.min.js web/static/js/htmx.min.js"
"build:js": "cp node_modules/htmx.org/dist/htmx.min.js web/static/js/htmx.min.js && cp ./node_modules/htmx-ext-preload/dist/preload.min.js ./web/static/js/preload.min.js"
},
"keywords": [],
"author": "",
@@ -20,6 +20,7 @@
"tailwindcss": "^4.1.18"
},
"dependencies": {
"htmx-ext-preload": "^2.1.2",
"htmx.org": "^2.0.8"
}
}
+10
View File
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
htmx-ext-preload:
specifier: ^2.1.2
version: 2.1.2
htmx.org:
specifier: ^2.0.8
version: 2.0.8
@@ -277,6 +280,9 @@ packages:
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
htmx-ext-preload@2.1.2:
resolution: {integrity: sha512-foD06XAITUUQApCUQnPexyJ6B7+4vFGMQ+t42unTVTGRu/CYHdAAt6oHg7eekPHT7NRnbM5hjnGVKtClryPabg==}
htmx.org@2.0.8:
resolution: {integrity: sha512-fm297iru0iWsNJlBrjvtN7V9zjaxd+69Oqjh4F/Vq9Wwi2kFisLcrLCiv5oBX0KLfOX/zG8AUo9ROMU5XUB44Q==}
@@ -617,6 +623,10 @@ snapshots:
graceful-fs@4.2.11: {}
htmx-ext-preload@2.1.2:
dependencies:
htmx.org: 2.0.8
htmx.org@2.0.8: {}
is-extglob@2.1.1: {}
+1
View File
@@ -8,6 +8,7 @@ templ ImageTile(src string) {
src={ src }
srcset={ images.SourceSet(src) }
fetchpriority="high"
loading="eager"
class="row-start-1 col-start-1 pointer-events-none w-full h-96 object-cover"
/>
<div class="row-start-1 col-start-1">
+3 -3
View File
@@ -14,17 +14,17 @@ templ Base(title string) {
<link rel="icon" type="image/png" href="/favicon.png"/>
<link fetchpriority="high" href="/css/output.css" rel="stylesheet"/>
<script fetchpriority="low" src="/js/htmx.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/htmx-ext-preload@2.1.2" integrity="sha384-PRIcY6hH1Y5784C76/Y8SqLyTanY9rnI3B8F3+hKZFNED55hsEqMJyqWhp95lgfk" crossorigin="anonymous"></script>
<script src="/js/preload.min.js"></script>
</head>
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="preload">
<header
class="fixed z-50 mix-blend-difference p-1 w-full flex justify-between items-start"
>
<a class="text-white text-2xl" href={ "/" + translate.Path(ctx, "") }>schreifuchs.ch</a>
<a class="text-white text-2xl" href={ translate.Path(ctx, "") }>schreifuchs.ch</a>
<nav class="flex gap-2 p-2">
for _, lang := range translate.SupportedLanguages(ctx) {
<a
href={ "/" + translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) }
href={ translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) }
hreflang={ lang }
data-no-translate
class="text-white hover:underline uppercase"
+1 -1
View File
@@ -19,7 +19,7 @@ func Render(ctx context.Context, w io.Writer, r *http.Request, component templ.C
slog.Debug("HX-Request", "value", r.Header.Get("HX-Request"))
if r.Header.Get("HX-Request") != "true" {
ctx = templ.WithChildren(ctx, component)
component = Base("hello")
component = Base("Schreifuchs")
}
if err := component.Render(ctx, w); err != nil {
+1 -1
View File
@@ -9,7 +9,7 @@ import (
templ Home(pages []page.PageHeader) {
for _, page := range pages {
@components.ImageTile("/images/" + page.CoverImageUID) {
<a class="flex items-center justify-center h-full " href={ translate.Path(ctx, page.UID) } preload="mouseover">
<a class="flex items-center justify-center h-full " href={ translate.Path(ctx, "/"+page.UID) } preload="mouseover">
<h2
class="text-3xl font-bold text-white hover:underline text-shadow-lg"
>
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
(function(){htmx.defineExtension("preload",{onEvent:function(e,t){if(e==="htmx:afterProcessNode"){const n=t.target||t.detail.elt;const r=[...n.hasAttribute("preload")?[n]:[],...n.querySelectorAll("[preload]")];r.forEach(function(e){i(e);e.querySelectorAll("[href],[hx-get],[data-hx-get]").forEach(i)});return}if(e==="htmx:beforeRequest"){const o=t.detail.requestConfig.headers;if(!("HX-Preloaded"in o&&o["HX-Preloaded"]==="true")){return}t.preventDefault();const a=t.detail.xhr;a.onload=function(){s(t.detail.elt,a.responseText)};a.onerror=null;a.onabort=null;a.ontimeout=null;a.send()}}});function i(t){if(t.preloadState!==undefined){return}if(!l(t)){return}if(t instanceof HTMLFormElement){const o=t;if(!(o.hasAttribute("method")&&o.method==="get"||o.hasAttribute("hx-get")||o.hasAttribute("hx-data-get"))){return}for(let e=0;e<o.elements.length;e++){const a=o.elements.item(e);i(a);if("labels"in a){a.labels.forEach(i)}}return}let e=p(t,"preload");t.preloadAlways=e&&e.includes("always");if(t.preloadAlways){e=e.replace("always","").trim()}let n=e||"mousedown";const r=n==="mouseover";t.addEventListener(n,u(t,r),{passive:true});if(n==="mousedown"||n==="mouseover"){t.addEventListener("touchstart",u(t),{passive:true})}if(n==="mouseover"){t.addEventListener("mouseout",function(e){if(e.target===t&&t.preloadState==="TIMEOUT"){t.preloadState="READY"}},{passive:true})}t.preloadState="READY";htmx.trigger(t,"preload:init")}function u(t,n=false){return function(){if(t.preloadState!=="READY"){return}if(n){t.preloadState="TIMEOUT";const e=100;window.setTimeout(function(){if(t.preloadState==="TIMEOUT"){t.preloadState="READY";r(t)}},e);return}r(t)}}function r(n){if(n.preloadState!=="READY"){return}n.preloadState="LOADING";const e=n.getAttribute("hx-get")||n.getAttribute("data-hx-get");if(e){m(e,n);return}const t=p(n,"hx-boost")==="true";if(n.hasAttribute("href")){const r=n.getAttribute("href");if(t){m(r,n)}else{h(r,n)}return}if(g(n)){const r=n.form.getAttribute("action")||n.form.getAttribute("hx-get")||n.form.getAttribute("data-hx-get");const o=htmx.values(n.form);const a=!(n.form.getAttribute("hx-get")||n.form.getAttribute("data-hx-get")||t);const i=a?h:m;if(n.type==="submit"){i(r,n.form,o);return}const u=n.name||n.control.name;if(n.tagName==="SELECT"){Array.from(n.options).forEach(e=>{if(e.selected)return;o.set(u,e.value);const t=d(n.form,o);i(r,n.form,t)});return}const s=n.getAttribute("type")||n.control.getAttribute("type");const l=n.value||n.control?.value;if(s==="radio"){o.set(u,l)}else if(s==="checkbox"){const c=o.getAll(u);if(c.includes(l)){o[u]=c.filter(e=>e!==l)}else{o.append(u,l)}}const f=d(n.form,o);i(r,n.form,f);return}}function d(e,t){const n=e.elements;const r=new FormData;for(let e=0;e<n.length;e++){const o=n.item(e);if(t.has(o.name)&&o.tagName==="SELECT"){r.append(o.name,t.get(o.name));continue}if(t.has(o.name)&&t.getAll(o.name).includes(o.value)){r.append(o.name,o.value)}}return r}function m(e,t,n=undefined){htmx.ajax("GET",e,{source:t,values:n,headers:{"HX-Preloaded":"true"}})}function h(e,t,n=undefined){const r=new XMLHttpRequest;if(n){e+="?"+new URLSearchParams(n.entries()).toString()}r.open("GET",e);r.setRequestHeader("HX-Preloaded","true");r.onload=function(){s(t,r.responseText)};r.send()}function s(e,t){e.preloadState=e.preloadAlways?"READY":"DONE";if(p(e,"preload-images")==="true"){document.createElement("div").innerHTML=t}}function p(e,t){if(e==undefined){return undefined}return e.getAttribute(t)||e.getAttribute("data-"+t)||p(e.parentElement,t)}function l(e){const n=["href","hx-get","data-hx-get"];const t=t=>n.some(e=>t.hasAttribute(e))||t.method==="get";const r=e.form instanceof HTMLFormElement&&t(e.form)&&g(e);if(!t(e)&&!r){return false}if(e instanceof HTMLInputElement&&e.closest("label")){return false}return true}function g(e){if(e instanceof HTMLInputElement||e instanceof HTMLButtonElement){const t=e.getAttribute("type");return["checkbox","radio","submit"].includes(t)}if(e instanceof HTMLLabelElement){return e.control&&g(e.control)}return e instanceof HTMLSelectElement}})();