/
template.go
61 lines (45 loc) · 1.17 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
package www
import (
"fmt"
"html/template"
"log/slog"
"net/http"
"github.com/sfomuseum/go-http-auth"
"github.com/whosonfirst/go-whosonfirst-spelunker-httpd"
)
type TemplateHandlerOptions struct {
Authenticator auth.Authenticator
Templates *template.Template
TemplateName string
PageTitle string
URIs *httpd.URIs
}
type TemplateHandlerVars struct {
Id int64
PageTitle string
URIs *httpd.URIs
Properties string
}
func TemplateHandler(opts *TemplateHandlerOptions) (http.Handler, error) {
t := opts.Templates.Lookup(opts.TemplateName)
if t == nil {
return nil, fmt.Errorf("Failed to locate ihelp' template")
}
logger := slog.Default()
fn := func(rsp http.ResponseWriter, req *http.Request) {
logger = logger.With("request", req.URL)
logger = logger.With("address", req.RemoteAddr)
vars := TemplateHandlerVars{
PageTitle: opts.PageTitle,
URIs: opts.URIs,
}
rsp.Header().Set("Content-Type", "text/html")
err := t.Execute(rsp, vars)
if err != nil {
slog.Error("Failed to return ", "error", err)
http.Error(rsp, "womp womp", http.StatusInternalServerError)
}
}
h := http.HandlerFunc(fn)
return h, nil
}