This commit is contained in:
Laurent Ulrich
2025-08-19 09:56:13 +02:00
parent 9f88d84513
commit 8c76f5e6f0
4 changed files with 46 additions and 24 deletions

15
blog.go
View File

@@ -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
}

View File

@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width" />
<title>{{.BlogTitle}}</title>
</head>
<h1>{{.BlogTitle}}</h1>
<h1><a href="/proxy/8080/">{{.BlogTitle}}</a></h1>
<body>
<h2>{{.Title}}</h2>
<div>

View File

@@ -4,14 +4,27 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{{.Title}}</title>
<style>
a:link {
color: black;
text-decoration: none;
}
a:visited {
color: black;
text-decoration: none;
}
a:hover {
color: orange;
text-decoration: none;
}
</style>
</head>
<body>
<h1>{{.Title}}</h1>
<h1><a href="/proxy/8080/">{{.Title}}</a></h1>
{{range .Posts}}
<article>
<a href=/proxy/8080/post/{{ .Id }}>
<h2>{{.Title}}</h2>
</a>
<h2><a href=/proxy/8080/post/{{ .Id }}>{{.Title}}</a></h2>
<div>
{{.HTML}}
</div>

32
web.go
View File

@@ -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)
})