hatecomputers.club/api/template/template.go

77 lines
1.9 KiB
Go
Raw Normal View History

2024-04-03 19:53:50 -04:00
package template
2024-03-26 18:00:05 -04:00
import (
"bytes"
"errors"
"html/template"
"log"
"net/http"
"os"
2024-04-03 19:53:50 -04:00
"git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types"
2024-03-26 18:00:05 -04:00
)
2024-04-03 19:53:50 -04:00
func renderTemplate(context *types.RequestContext, templateName string, showBaseHtml bool) (bytes.Buffer, error) {
2024-03-26 18:00:05 -04:00
templatePath := context.Args.TemplatePath
basePath := templatePath + "/base_empty.html"
if showBaseHtml {
basePath = templatePath + "/base.html"
}
templateLocation := templatePath + "/" + templateName
tmpl, err := template.New("").ParseFiles(templateLocation, basePath)
if err != nil {
return bytes.Buffer{}, err
}
2024-03-28 00:55:22 -04:00
dataPtr := context.TemplateData
if dataPtr == nil {
dataPtr = &map[string]interface{}{}
2024-03-27 17:02:31 -04:00
}
2024-03-28 00:55:22 -04:00
data := *dataPtr
if data["User"] == nil {
data["User"] = context.User
2024-03-27 17:02:31 -04:00
}
2024-03-26 18:00:05 -04:00
var buffer bytes.Buffer
err = tmpl.ExecuteTemplate(&buffer, "base", data)
if err != nil {
return bytes.Buffer{}, err
}
return buffer, nil
}
2024-04-03 19:53:50 -04:00
func TemplateContinuation(path string, showBase bool) types.Continuation {
return func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
2024-03-28 00:55:22 -04:00
html, err := renderTemplate(context, path, true)
2024-03-26 18:00:05 -04:00
if errors.Is(err, os.ErrNotExist) {
resp.WriteHeader(404)
2024-03-28 00:55:22 -04:00
html, err = renderTemplate(context, "404.html", true)
2024-03-26 18:00:05 -04:00
if err != nil {
log.Println("error rendering 404 template", err)
resp.WriteHeader(500)
return failure(context, req, resp)
}
resp.Header().Set("Content-Type", "text/html")
resp.Write(html.Bytes())
return failure(context, req, resp)
}
if err != nil {
log.Println("error rendering template", err)
resp.WriteHeader(500)
resp.Write([]byte("error rendering template"))
return failure(context, req, resp)
}
resp.Header().Set("Content-Type", "text/html")
resp.Write(html.Bytes())
return success(context, req, resp)
}
}
}