registering templates

This commit is contained in:
Hazel Noack 2025-07-17 11:10:17 +02:00
parent 13fae1c23f
commit a62b445f19
3 changed files with 81 additions and 47 deletions

View File

@ -1,42 +0,0 @@
package server
import (
"bytes"
"embed"
"io/fs"
"log"
"net/http"
"text/template"
"github.com/labstack/echo/v4"
)
var FrontendFiles embed.FS
func getFileContent() string {
content, err := FrontendFiles.ReadFile("frontend/index.html")
if err != nil {
log.Fatal(err)
}
return string(content)
}
func getIndex(c echo.Context) error {
IndexTemplate := template.Must(template.New("index").Parse(getFileContent()))
var tpl bytes.Buffer
IndexTemplate.Execute(&tpl, Config.Template)
return c.HTML(http.StatusOK, tpl.String())
}
func getFileSystem() http.FileSystem {
fsys, err := fs.Sub(FrontendFiles, "frontend")
if err != nil {
panic(err)
}
return http.FS(fsys)
}

View File

@ -2,7 +2,6 @@ package server
import (
"log"
"net/http"
"strconv"
"time"
@ -57,10 +56,13 @@ func Start(profile string) error {
}
// https://echo.labstack.com/docs/cookbook/embed-resources
staticHandler := http.FileServer(getFileSystem())
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))
e.GET("/scripts/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))
e.GET("/", getIndex)
/*
staticHandler := http.FileServer(getFileSystem())
e.GET("/assets/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))
e.GET("/scripts/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))
e.GET("/", getIndex)
*/
StartTemplating(e)
e.Logger.Fatal(e.Start(":" + strconv.Itoa(Config.Server.Port)))
return nil

View File

@ -0,0 +1,74 @@
package server
import (
"bytes"
"embed"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"text/template"
"github.com/labstack/echo/v4"
)
var FrontendFiles embed.FS
func getFileContent() string {
content, err := FrontendFiles.ReadFile("frontend/index.html")
if err != nil {
log.Fatal(err)
}
return string(content)
}
func getIndex(c echo.Context) error {
IndexTemplate := template.Must(template.New("index").Parse(getFileContent()))
var tpl bytes.Buffer
IndexTemplate.Execute(&tpl, Config.Template)
return c.HTML(http.StatusOK, tpl.String())
}
func getFileSystem() http.FileSystem {
fsys, err := fs.Sub(FrontendFiles, "frontend")
if err != nil {
panic(err)
}
return http.FS(fsys)
}
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func ServeTemplate(c echo.Context) error {
fmt.Println(c.Request().URL)
return c.Render(http.StatusOK, "style.css", Config.Template)
}
func StartTemplating(e *echo.Echo) {
// register templates as renderer
t := &Template{
templates: template.Must(template.ParseFS(
FrontendFiles,
"frontend/index.html",
"frontend/**/*.css",
"frontend/**/*.js",
)),
}
fmt.Println(t.templates.ParseName)
e.Renderer = t
e.GET("/*", ServeTemplate)
e.GET("/**/*", ServeTemplate)
}