From 8c76f5e6f0190f8ca838f56df0aadee1bbc1db4d Mon Sep 17 00:00:00 2001 From: Laurent Ulrich Date: Tue, 19 Aug 2025 09:56:13 +0200 Subject: [PATCH] zz --- blog.go | 15 +++++++++++++++ html/entry.tmpl | 2 +- html/index.tmpl | 21 +++++++++++++++++---- web.go | 32 +++++++++++++------------------- 4 files changed, 46 insertions(+), 24 deletions(-) diff --git a/blog.go b/blog.go index b855f5b..ebe50c5 100644 --- a/blog.go +++ b/blog.go @@ -22,3 +22,18 @@ type Blog struct { Posts []Post mutex sync.Mutex } + +func (b *Blog) GetPost(Id string) (Post, bool) { + var ret Post + b.mutex.Lock() + defer b.mutex.Unlock() + for _, p := range b.Posts { + if p.Id == Id { + ret = p + ret.BlogTitle = b.Title + ret.Lang = b.Lang + return ret, true + } + } + return ret, false +} diff --git a/html/entry.tmpl b/html/entry.tmpl index 90a06ae..8db3a12 100644 --- a/html/entry.tmpl +++ b/html/entry.tmpl @@ -5,7 +5,7 @@ {{.BlogTitle}} -

{{.BlogTitle}}

+

{{.BlogTitle}}

{{.Title}}

diff --git a/html/index.tmpl b/html/index.tmpl index 5236360..f0c337a 100644 --- a/html/index.tmpl +++ b/html/index.tmpl @@ -4,14 +4,27 @@ {{.Title}} + -

{{.Title}}

+

{{.Title}}

{{range .Posts}}
- -

{{.Title}}

-
+

{{.Title}}

+
{{.HTML}}
diff --git a/web.go b/web.go index 397f114..67d74bd 100644 --- a/web.go +++ b/web.go @@ -8,6 +8,7 @@ import ( func StartServer(blog *Blog) { + /* Handle home page (/): list of blog entries */ http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { tpl, err := template.New("index").Parse(indexTemplate) @@ -22,29 +23,22 @@ func StartServer(blog *Blog) { } }) + /* Handle one post display(/post/{post ID}) */ http.HandleFunc("GET /post/{id}", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") - log.Println("showing post:", id) - blog.mutex.Lock() - defer blog.mutex.Unlock() - for _, p := range blog.Posts { - if p.Id == id { - tpl, err := template.New("entry").Parse(entryTemplate) - if err != nil { - log.Fatal(err) - } - post := p - post.BlogTitle = blog.Title - post.Lang = blog.Lang - err = tpl.ExecuteTemplate(w, "entry", post) - if err != nil { - log.Fatal(err) - } - return - } + post, found := blog.GetPost(id) + if !found { + w.WriteHeader(404) + } + tpl, err := template.New("entry").Parse(entryTemplate) + if err != nil { + log.Fatal(err) + } + err = tpl.ExecuteTemplate(w, "entry", post) + if err != nil { + log.Fatal(err) } - w.WriteHeader(404) })