-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.go
57 lines (46 loc) · 1.16 KB
/
format.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
package main
import (
"encoding/json"
htmlTemplate "html/template"
"io"
textTemplate "text/template"
)
// StateFormat is the data to format in the response.
type StateFormat struct {
Label string `json:"label"`
State string `json:"state"`
}
func writeBody(w io.Writer, contentType string, stateFormat StateFormat) {
switch contentType {
case "text/plain":
writeTextBody(w, stateFormat)
case "application/json":
writeJSONBody(w, stateFormat)
case "text/html":
writeHTMLBody(w, stateFormat)
default:
writeHTMLBody(w, stateFormat)
}
}
func writeHTMLBody(w io.Writer, stateFormat StateFormat) {
tpl := `<!DOCTYPE html>
<html>
<head>
<title>{{.Label}}: {{.State}}</title>
</head>
<body>
<h2>{{.Label}}</h2>
<h1 style="text-transform: capitalize;">{{.State}}<h1>
</body>
</html>`
t, _ := htmlTemplate.New("systemd-state").Parse(tpl)
_ = t.Execute(w, stateFormat)
}
func writeTextBody(w io.Writer, stateFormat StateFormat) {
tpl := `{{.Label}}: {{.State}}`
t, _ := textTemplate.New("systemd-state").Parse(tpl)
_ = t.Execute(w, stateFormat)
}
func writeJSONBody(w io.Writer, stateFormat StateFormat) {
_ = json.NewEncoder(w).Encode(stateFormat)
}