hatecomputers.club/api/template.go

66 lines
1.7 KiB
Go

package api
import (
"bytes"
"errors"
"html/template"
"log"
"net/http"
"os"
)
func renderTemplate(context *RequestContext, templateName string, showBaseHtml bool, data interface{}) (bytes.Buffer, error) {
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
}
var buffer bytes.Buffer
err = tmpl.ExecuteTemplate(&buffer, "base", data)
if err != nil {
return bytes.Buffer{}, err
}
return buffer, nil
}
func TemplateContinuation(path string, data interface{}, showBase bool) Continuation {
return func(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
return func(success Continuation, failure Continuation) ContinuationChain {
html, err := renderTemplate(context, path, true, data)
if errors.Is(err, os.ErrNotExist) {
resp.WriteHeader(404)
html, err = renderTemplate(context, "404.html", true, nil)
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.WriteHeader(200)
resp.Header().Set("Content-Type", "text/html")
resp.Write(html.Bytes())
return success(context, req, resp)
}
}
}