Add templating
This commit is contained in:
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -36,7 +37,7 @@ type Config struct {
|
||||
// Server hosts the Luxtools HTTP handlers.
|
||||
type Server struct {
|
||||
mux *http.ServeMux
|
||||
indexPage []byte
|
||||
templates *template.Template
|
||||
staticFS fs.FS
|
||||
mediaFS http.FileSystem
|
||||
|
||||
@@ -60,9 +61,10 @@ func New(cfg Config) (*Server, error) {
|
||||
return nil, fmt.Errorf("media directory must be a directory: %s", mediaDir)
|
||||
}
|
||||
|
||||
indexPage, err := webbundle.Content.ReadFile("templates/index.html")
|
||||
// Parse all templates
|
||||
tmpl, err := template.ParseFS(webbundle.Content, "templates/*.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read index template: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse templates: %w", err)
|
||||
}
|
||||
|
||||
staticFS, err := fs.Sub(webbundle.Content, "static")
|
||||
@@ -72,7 +74,7 @@ func New(cfg Config) (*Server, error) {
|
||||
|
||||
s := &Server{
|
||||
mux: http.NewServeMux(),
|
||||
indexPage: indexPage,
|
||||
templates: tmpl,
|
||||
staticFS: staticFS,
|
||||
mediaFS: http.Dir(mediaDir),
|
||||
}
|
||||
@@ -103,7 +105,12 @@ func (s *Server) registerRoutes() {
|
||||
func (s *Server) handleRequest(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/":
|
||||
s.sendHTML(w, http.StatusOK, s.indexPage)
|
||||
data := DefaultMenuBar()
|
||||
s.renderTemplate(w, http.StatusOK, "index.html", data)
|
||||
case "/admin":
|
||||
data := AdminMenuBar()
|
||||
data.Title = "Admin Panel"
|
||||
s.renderTemplate(w, http.StatusOK, "admin.html", data)
|
||||
case "/counter":
|
||||
s.handleCounter(w, r)
|
||||
case "/time":
|
||||
@@ -127,6 +134,16 @@ func (s *Server) handleCounter(w http.ResponseWriter, r *http.Request) {
|
||||
s.sendHTMLString(w, http.StatusOK, renderCounter(count))
|
||||
}
|
||||
|
||||
func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string, data interface{}) {
|
||||
w.Header().Set("Content-Type", htmlContentType)
|
||||
w.WriteHeader(status)
|
||||
|
||||
if err := s.templates.ExecuteTemplate(w, name, data); err != nil {
|
||||
log.Printf("template execution failed: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) sendHTML(w http.ResponseWriter, status int, body []byte) {
|
||||
w.Header().Set("Content-Type", htmlContentType)
|
||||
w.WriteHeader(status)
|
||||
|
||||
Reference in New Issue
Block a user