101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"html/template"
|
||
"net/http"
|
||
"os"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"git.send.nrw/sendnrw/b1tsblog/internal/article"
|
||
)
|
||
|
||
func getenv(k, d string) string {
|
||
if v := os.Getenv(k); v != "" {
|
||
return v
|
||
}
|
||
return d
|
||
}
|
||
|
||
func enabled(k string, def bool) bool {
|
||
b, err := strconv.ParseBool(strings.ToLower(os.Getenv(k)))
|
||
if err != nil {
|
||
return def
|
||
}
|
||
return b
|
||
}
|
||
|
||
func cacheControl(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||
next.ServeHTTP(w, r)
|
||
})
|
||
}
|
||
|
||
var (
|
||
tplList *template.Template
|
||
tplArticle *template.Template
|
||
)
|
||
|
||
func main() {
|
||
|
||
funcs := template.FuncMap{
|
||
"now": time.Now, // jetzt‑Zeit bereitstellen
|
||
}
|
||
|
||
// Basislayout zuerst parsen
|
||
base := template.Must(
|
||
template.New("base").Funcs(funcs).
|
||
ParseFiles("internal/web/templates/base.html"),
|
||
)
|
||
|
||
// LIST‑Seite: base + list.html
|
||
tplList = template.Must(base.Clone())
|
||
template.Must(tplList.Funcs(funcs).ParseFiles("internal/web/templates/list.html"))
|
||
|
||
// ARTICLE‑Instanz
|
||
tplArticle = template.Must(base.Clone())
|
||
template.Must(tplArticle.Funcs(funcs).ParseFiles("internal/web/templates/article.html"))
|
||
|
||
mux := http.NewServeMux()
|
||
|
||
staticDir := "internal/web/static"
|
||
|
||
articles, err := article.LoadDir("content")
|
||
if err != nil {
|
||
fmt.Println(err)
|
||
}
|
||
|
||
// Handler für /
|
||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||
if r.URL.Path != "/" {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
if err := tplList.ExecuteTemplate(w, "base", articles); err != nil {
|
||
http.Error(w, err.Error(), 500)
|
||
}
|
||
})
|
||
|
||
mux.HandleFunc("/post/", func(w http.ResponseWriter, r *http.Request) {
|
||
slug := strings.TrimPrefix(r.URL.Path, "/post/")
|
||
for _, a := range articles {
|
||
if a.Slug == slug {
|
||
if err := tplArticle.ExecuteTemplate(w, "base", a); err != nil {
|
||
http.Error(w, err.Error(), 500)
|
||
}
|
||
return
|
||
}
|
||
}
|
||
http.NotFound(w, r)
|
||
})
|
||
|
||
mux.Handle("/static/",
|
||
cacheControl(http.StripPrefix("/static/",
|
||
http.FileServer(http.Dir(staticDir)))))
|
||
|
||
http.ListenAndServe(":8080", mux)
|
||
}
|