-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.go
84 lines (78 loc) · 1.48 KB
/
helpers.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
package main
import (
"html/template"
"net/http"
)
func (s *Server) notFound(
w http.ResponseWriter,
r *http.Request,
title string,
message string,
) {
w.WriteHeader(http.StatusNotFound)
s.renderTemplate(
w, r,
struct {
Title string
Message string
}{
Title: title,
Message: message,
},
"layout",
"html/layout.html",
"html/notfound.html")
}
func (s *Server) badRequest(
w http.ResponseWriter,
r *http.Request,
statusCode int,
message string,
) {
w.WriteHeader(statusCode)
w.Write([]byte(message))
}
func (s *Server) serverError(
w http.ResponseWriter,
r *http.Request,
) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Ops something went wrong. Please check the server logs."))
}
func (s *Server) renderTemplate(
w http.ResponseWriter,
r *http.Request,
data interface{},
name string,
files ...string,
) {
t, err := template.ParseFiles(files...)
if err != nil {
http.Error(w, "Template parsing error: "+err.Error(), http.StatusInternalServerError)
return
}
err = t.ExecuteTemplate(w, name, data)
if err != nil {
http.Error(w, "Template execution error: "+err.Error(), http.StatusInternalServerError)
}
}
func (s *Server) renderMessage(
w http.ResponseWriter,
r *http.Request,
title string,
paragraphs ...interface{},
) {
s.renderTemplate(
w, r,
struct {
Title string
Paragraphs []interface{}
}{
Title: title,
Paragraphs: paragraphs,
},
"layout",
"html/layout.html",
"html/message.html",
)
}