Add hot tempalte reloading, WIP pos

This commit is contained in:
Elnu 2023-07-21 10:34:56 -07:00
parent e00df6aac6
commit 442f727d8a
4 changed files with 73 additions and 15 deletions

View file

@ -3,25 +3,68 @@ package httputils
import (
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
"time"
)
type Handler = func(http.ResponseWriter, *http.Request)
const templateFolder = "templates"
var templatePaths, templateModTimes, _ = getTemplates()
var templates *template.Template = template.Must(template.ParseFiles(templatePaths...))
func getTemplates() ([]string, map[string]time.Time, error) {
var modTimes map[string]time.Time = make(map[string]time.Time)
err := filepath.Walk(templateFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(path, ".html") {
modTimes[path] = info.ModTime()
}
return nil
})
paths := make([]string, len(modTimes))
i := 0
for path := range modTimes {
paths[i] = path
i++
}
return paths, modTimes, err
}
func reloadTemplateIfModified(path string) {
fileInfo, _ := os.Stat(path)
modTime := fileInfo.ModTime()
if modTime.After(templateModTimes[path]) {
fmt.Printf("Reloading template %s...\n", path)
templates.ParseFiles(path)
templateModTimes[path] = modTime
}
}
func reloadTemplatesIfModified() {
for _, path := range templatePaths {
reloadTemplateIfModified(path)
}
}
const reloadTemplates = true
func GenerateHandler(
file string,
handler func(http.ResponseWriter, *http.Request) bool,
data func(http.ResponseWriter, *http.Request) any,
methods []string,
) Handler {
var tmpl *template.Template
//if file != "" {
// tmpl = template.Must(template.ParseFiles(fmt.Sprintf("templates/%s", file)))
//}
return func(w http.ResponseWriter, r *http.Request) {
// Remove in production, enables live template reloading
if file != "" {
tmpl = template.Must(template.ParseFiles(fmt.Sprintf("templates/%s", file)))
// All templates must be reloaded in case of dependencies
if reloadTemplates {
reloadTemplatesIfModified()
}
for _, method := range methods {
if method == r.Method {
@ -32,9 +75,9 @@ func GenerateHandler(
return
ok:
renderTemplate := handler(w, r)
if renderTemplate && tmpl != nil {
if renderTemplate && file != "" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, data(w, r))
templates.ExecuteTemplate(w, file, data(w, r))
}
}
}