-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
template.go
97 lines (84 loc) · 2.24 KB
/
template.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package server
import (
"context"
"io"
"net/http"
"net/url"
"path"
template_text "text/template"
"time"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/template"
"github.com/grafana/loki/v3/clients/pkg/promtail/server/ui"
)
// templateOptions is a set of options to render a template.
type templateOptions struct {
ExternalURL *url.URL
Name, PageTitle, BuildVersion string
Data interface{}
TemplateFuncs template_text.FuncMap
}
// tmplFuncs create a default template function for a given template options
func (opts templateOptions) tmplFuncs() template_text.FuncMap {
return template_text.FuncMap{
"since": func(t time.Time) time.Duration {
return time.Since(t) / time.Millisecond * time.Millisecond
},
"pathPrefix": func() string { return opts.ExternalURL.Path },
"pageTitle": func() string { return opts.PageTitle },
"buildVersion": func() string { return opts.BuildVersion },
}
}
// executeTemplate execute a template and write result to the http.ResponseWriter
func executeTemplate(ctx context.Context, w http.ResponseWriter, tmplOpts templateOptions) {
text, err := getTemplate(tmplOpts.Name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
tmpl := template.NewTemplateExpander(
ctx,
text,
tmplOpts.Name,
tmplOpts.Data,
model.Now(),
nil,
tmplOpts.ExternalURL,
nil,
)
tmpl.Funcs(tmplOpts.tmplFuncs())
tmpl.Funcs(tmplOpts.TemplateFuncs)
result, err := tmpl.ExpandHTML(nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, _ = io.WriteString(w, result)
}
func getTemplate(name string) (string, error) {
var tmpl string
appendf := func(name string) error {
f, err := ui.Assets.Open(path.Join("/templates", name))
if err != nil {
return err
}
defer func() {
_ = f.Close()
}()
b, err := io.ReadAll(f)
if err != nil {
return err
}
tmpl += string(b)
return nil
}
err := appendf("_base.html")
if err != nil {
return "", errors.Wrap(err, "error reading base template")
}
err = appendf(name)
if err != nil {
return "", errors.Wrapf(err, "error reading page template %s", name)
}
return tmpl, nil
}