-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.go
More file actions
106 lines (87 loc) · 2.23 KB
/
ui.go
File metadata and controls
106 lines (87 loc) · 2.23 KB
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
98
99
100
101
102
103
104
105
106
package main
import (
"context"
"embed"
"html/template"
"net/http"
)
//go:embed templates
var tmplFS embed.FS
type Exec struct {
ID string
Command string
Status string
}
func listExecs(_ context.Context) []Exec {
return []Exec{
{ID: "1", Command: "uptime", Status: "done"},
{ID: "2", Command: "ls -la", Status: "running"},
}
}
type renderer struct{ t *template.Template }
func newRenderer() *renderer {
t := template.Must(
template.New("root").
Funcs(template.FuncMap{}).
ParseFS(
tmplFS,
"templates/layouts/*.tmpl",
"templates/pages/*.tmpl",
"templates/fragments/*.tmpl",
))
return &renderer{t: t}
}
func (r *renderer) write(w http.ResponseWriter, name string, data any) {
t := r.t.Lookup(name)
if t == nil {
http.Error(w, "template not found: "+name, http.StatusNotFound)
return
}
if err := t.Execute(w, data); err != nil {
http.Error(w, "template exec error: "+err.Error(), http.StatusInternalServerError)
}
}
func newUIHandler(rr *renderer) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
rr.write(w, "pages/execs.tmpl", nil)
})
}
func newHXHandler(rr *renderer) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := struct{ Execs []Exec }{Execs: listExecs(r.Context())}
rr.write(w, "fragments/exec_table.tmpl", data)
})
}
func newUIRoutes(rr *renderer, sess *sessions, password string) *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("GET /", chain(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ui/execs", http.StatusFound)
}),
withSecurityHeaders,
withAuth(password, false, sess),
withMeta,
withTracing,
))
mux.Handle("GET /execs", chain(
newUIHandler(rr),
withSecurityHeaders,
withAuth(password, false, sess),
withMeta,
withTracing,
))
return mux
}
func newHXRoutes(rr *renderer, sess *sessions, password string) *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("GET /execs", chain(
newHXHandler(rr),
withSecurityHeaders,
withAuth(password, false, sess),
withMeta,
withTracing,
))
return mux
}