feat: html static templates

This commit is contained in:
ange 2024-12-14 08:34:47 +00:00
parent 9d0da00371
commit e9fc659a5a
Signed by: ange
GPG key ID: 9E0C4157BB7BEB1D
12 changed files with 91 additions and 100 deletions

View file

@ -7,9 +7,8 @@ import (
func main() {
http.HandleFunc("/", route)
err := http.ListenAndServe(":3000", nil)
if err != nil {
generateTmpl()
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal(err)
}
}

View file

@ -34,8 +34,9 @@ func route(w http.ResponseWriter, r *http.Request) {
http.Error(
w, "405 method not allowed", http.StatusMethodNotAllowed,
)
fmt.Println(r.Method, r.URL.Path)
return
}
fmt.Println(r.Method, r.URL.Path)
rt.handler(w, r.WithContext(
context.WithValue(r.Context(), URLParam{}, matches[1:])),
)

29
src/tmpl.go Normal file
View file

@ -0,0 +1,29 @@
package main
import (
"bytes"
"html/template"
"path/filepath"
"regexp"
)
var TMPL map[string][]byte
// TODO not use a global
// TODO use range instead of if else in header.html
func generateTmpl() {
files, _ := filepath.Glob("html/*.html")
re := regexp.MustCompile("html(/.+).html")
TMPL = make(map[string][]byte, len(files))
for _, f := range files {
b := new(bytes.Buffer)
name := re.FindStringSubmatch(f)[1]
t, _ := template.ParseFiles(f)
t.ParseGlob("tmpl/*.tmpl")
t.Execute(b, map[string]any{
"name": name,
})
TMPL[name] = b.Bytes()
}
}

View file

@ -2,15 +2,15 @@ package main
import (
"net/http"
"path/filepath"
)
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("html", "index.html"))
r.URL.Path = "/contact"
html(w, r)
}
func style(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/html/style.css")
http.ServeFile(w, r, "html/style.css")
}
func static(w http.ResponseWriter, r *http.Request) {
@ -18,5 +18,9 @@ func static(w http.ResponseWriter, r *http.Request) {
}
func html(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("html", r.URL.Path + ".html"))
if t, found := TMPL[r.URL.Path]; found {
w.Write(t)
} else {
http.NotFound(w, r)
}
}