diff --git a/app/app.go b/app/app.go index f9d0d3c..df1aef2 100644 --- a/app/app.go +++ b/app/app.go @@ -3,10 +3,12 @@ package app import ( "GoWeb/config" "database/sql" + "embed" ) // App contains and supplies available configurations and connections type App struct { - Config config.Configuration - Db *sql.DB + Config config.Configuration // Configuration file + Db *sql.DB // Database connection + Res *embed.FS // Resources from the embedded filesystem } diff --git a/main.go b/main.go index 2d81e63..307cab1 100644 --- a/main.go +++ b/main.go @@ -5,12 +5,16 @@ import ( "GoWeb/config" "GoWeb/database" "GoWeb/routes" + "embed" "log" "net/http" "os" "time" ) +//go:embed templates static +var res embed.FS + func main() { // Create instance of App appLoaded := app.App{} @@ -18,6 +22,9 @@ func main() { // Load config file to application appLoaded.Config = config.LoadConfig() + // Load templates + appLoaded.Res = &res + // Create logs directory if it doesn't exist if _, err := os.Stat("logs"); os.IsNotExist(err) { err := os.Mkdir("logs", 0755) diff --git a/templating/templateHelper.go b/templating/templateHelper.go index 8ca0039..ee00b37 100644 --- a/templating/templateHelper.go +++ b/templating/templateHelper.go @@ -7,11 +7,39 @@ import ( "net/http" ) +// RenderTemplate renders and serves a template from the embedded filesystem optionally with given data func RenderTemplate(app *app.App, w http.ResponseWriter, contentPath string, data any) { templatePath := app.Config.Template.BaseName - t, _ := template.ParseFiles(templatePath, contentPath) - err := t.Execute(w, data) + templateContent, err := app.Res.ReadFile(templatePath) + if err != nil { + log.Println(err) + http.Error(w, err.Error(), 500) + return + } + + t, err := template.New(templatePath).Parse(string(templateContent)) + if err != nil { + log.Println(err) + http.Error(w, err.Error(), 500) + return + } + + content, err := app.Res.ReadFile(contentPath) + if err != nil { + log.Println(err) + http.Error(w, err.Error(), 500) + return + } + + t, err = t.Parse(string(content)) + if err != nil { + log.Println(err) + http.Error(w, err.Error(), 500) + return + } + + err = t.Execute(w, data) if err != nil { log.Println(err) http.Error(w, err.Error(), 500)