summaryrefslogtreecommitdiff
path: root/api/template/template.go
blob: 4e0d4f97253cf4ebc3979534e3eef5f77133c675 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package template

import (
	"bytes"
	"errors"
	"html/template"
	"log"
	"net/http"
	"os"

	"git.simponic.xyz/simponic/whois/api/types"
)

func renderTemplate(context *types.RequestContext, templateName string, showBaseHtml bool) (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
	}

	dataPtr := context.TemplateData
	if dataPtr == nil {
		dataPtr = &map[string]interface{}{}
	}

	data := *dataPtr

	var buffer bytes.Buffer
	err = tmpl.ExecuteTemplate(&buffer, "base", data)

	if err != nil {
		return bytes.Buffer{}, err
	}
	return buffer, nil
}

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 {
			html, err := renderTemplate(context, path, showBase)
			if errors.Is(err, os.ErrNotExist) {
				resp.WriteHeader(404)
				html, err = renderTemplate(context, "404.html", true)
				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)
			}

			if showBase {
			    resp.Header().Set("Content-Type", "text/html")
			}
			resp.Write(html.Bytes())
			return success(context, req, resp)
		}
	}
}