From 006c0028106425abb3f718b2e86349dee5b7a2ea Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 26 May 2024 21:43:49 +0200 Subject: Refactor how preprocess functions work a bit --- src/http/posts.go | 57 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 28 deletions(-) (limited to 'src/http/posts.go') diff --git a/src/http/posts.go b/src/http/posts.go index 8488996..1bc65c8 100644 --- a/src/http/posts.go +++ b/src/http/posts.go @@ -5,10 +5,10 @@ import ( "context" "errors" "fmt" + "html/template" "net/http" "path/filepath" "strings" - txttpl "text/template" "time" "dev.mediocregopher.com/mediocre-blog.git/src/http/apiutil" @@ -18,7 +18,18 @@ import ( "dev.mediocregopher.com/mediocre-go-lib.git/mctx" ) -func (a *api) postPreprocessFuncImage(args ...string) (string, error) { +type postPreprocessFuncs struct { + urlBuilder render.URLBuilder + imageTpl *template.Template +} + +func newPostPreprocessFuncs(urlBuilder render.URLBuilder) postPreprocessFuncs { + imageTpl := template.New("image.html") + imageTpl = template.Must(imageTpl.Parse(mustReadTplFile("image.html"))) + return postPreprocessFuncs{urlBuilder, imageTpl} +} + +func (f postPreprocessFuncs) Image(args ...string) (string, error) { var ( id = args[0] @@ -29,39 +40,29 @@ func (a *api) postPreprocessFuncImage(args ...string) (string, error) { descr = args[1] } - tpl := txttpl.New("image.html") - tpl = txttpl.Must(tpl.Parse(mustReadTplFile("image.html"))) - - tplPayload := struct { - RootURL render.URLBuilder - ID string - Descr string - Resizable bool - }{ - RootURL: render.NewURLBuilder( - a.params.PublicURL, - a.params.PublicURL, // httpURL - a.params.GeminiPublicURL, - ), - ID: id, - Descr: descr, - Resizable: asset.IsImageResizable(id), - } + var ( + tplPayload = struct { + RootURL render.URLBuilder + ID string + Descr string + Resizable bool + }{ + RootURL: f.urlBuilder, + ID: id, + Descr: descr, + Resizable: asset.IsImageResizable(id), + } + buf = new(bytes.Buffer) + ) - buf := new(bytes.Buffer) - if err := tpl.ExecuteTemplate(buf, "image.html", tplPayload); err != nil { + err := f.imageTpl.ExecuteTemplate(buf, "image.html", tplPayload) + if err != nil { return "", err } return buf.String(), nil } -func (a *api) postPreprocessFuncs() post.PreprocessFunctions { - return post.PreprocessFunctions{ - Image: a.postPreprocessFuncImage, - } -} - func (a *api) getPostsHandler() http.Handler { var ( tpl = a.mustParseBasedTpl("posts.html") -- cgit v1.2.3