-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
294 lines (262 loc) · 7.66 KB
/
view.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package beepboop
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
// View is something that a PageHandler returns and is capable of rendering a page
type View struct {
StatusCode int
Error error
Data interface{}
Redirect string
header http.Header
cookies []*http.Cookie
renderer func(w http.ResponseWriter)
closer func() error
}
// Render renders the view
func (view *View) Render(w http.ResponseWriter) {
h := w.Header()
for key, values := range view.header {
key = http.CanonicalHeaderKey(key)
h[key] = append(h[key], values...)
}
for _, cookie := range view.cookies {
http.SetCookie(w, cookie)
}
view.renderer(w)
}
// RenderAPIResponse renders the API response of the view
func (view *View) RenderAPIResponse(w http.ResponseWriter) {
h := w.Header()
for key, values := range view.header {
key = http.CanonicalHeaderKey(key)
h[key] = append(h[key], values...)
}
for _, cookie := range view.cookies {
http.SetCookie(w, cookie)
}
w.WriteHeader(view.StatusCode)
if view.Error != nil {
w.Write([]byte(view.Error.Error()))
return
}
if view.Data != nil {
data, err := json.MarshalIndent(view.Data, "", "\t")
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Write(data)
return
}
if view.StatusCode == http.StatusOK {
w.Write([]byte("OK"))
return
}
w.Write([]byte(http.StatusText(view.StatusCode)))
}
// Close frees resources used by the view
func (view *View) Close() error {
if view.closer != nil {
return view.closer()
}
return nil
}
// ViewOption is used to customize the error message, error code or data in the view
type ViewOption func(view *View)
// WithError sets the view error and error code
func WithError(err error, errcode int) ViewOption {
return func(view *View) {
view.Error = err
view.StatusCode = errcode
}
}
// WithErrorMessage sets the view error message and error code
func WithErrorMessage(errmsg string, errcode int) ViewOption {
return WithError(fmt.Errorf("%s", errmsg), errcode)
}
// WithData sets the view data
func WithData(data interface{}) ViewOption {
return func(view *View) {
view.Data = data
}
}
// WithHeader adds a header field to the view
func WithHeader(key, value string) ViewOption {
return func(view *View) {
if view.header == nil {
view.header = make(http.Header)
}
view.header.Add(key, value)
}
}
// WithCookie adds a cookie to the view
func WithCookie(cookie *http.Cookie) ViewOption {
return func(view *View) {
view.cookies = append(view.cookies, cookie)
}
}
var defaultErrorRenderer = GetErrorRenderer(DefaultLayout)
// CustomErrorView returns a View that represents an error and uses a custom renderer
func CustomErrorView(r *http.Request, errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View {
v := &View{
StatusCode: errcode,
Error: fmt.Errorf("%s", errmsg),
}
for _, opt := range opts {
opt(v)
}
v.renderer = func(w http.ResponseWriter) {
renderer(w, r, errmsg, v.StatusCode)
}
return v
}
// CustomErrorView returns a View that represents an error and uses a custom renderer
func (r *PageRequest) CustomErrorView(errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View {
return CustomErrorView(r.Request, errmsg, errcode, renderer, opts...)
}
// ErrorView returns a View that represents an error
func ErrorView(r *http.Request, errmsg string, errcode int, opts ...ViewOption) *View {
return CustomErrorView(r, errmsg, errcode, defaultErrorRenderer, opts...)
}
// ErrorView returns a View that represents an error
func (r *PageRequest) ErrorView(errmsg string, errcode int, opts ...ViewOption) *View {
return ErrorView(r.Request, errmsg, errcode, opts...)
}
// EmbedView returns a View that embeds the given URL
func EmbedView(url string, opts ...ViewOption) *View {
v := &View{
StatusCode: http.StatusOK,
Data: url,
}
for _, opt := range opts {
opt(v)
}
v.renderer = func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(v.StatusCode)
fmt.Fprintf(w, `<iframe src="%s" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%%; height:100%%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>`, url)
}
return v
}
// EmbedView returns a View that embeds the given URL
func (r *PageRequest) EmbedView(url string, opts ...ViewOption) *View {
return EmbedView(url, opts...)
}
// RedirectView returns a View that redirects to the given URL
func RedirectView(r *http.Request, url string, opts ...ViewOption) *View {
v := &View{
StatusCode: http.StatusOK,
Redirect: url,
}
for _, opt := range opts {
opt(v)
}
v.renderer = func(w http.ResponseWriter) {
http.Redirect(w, r, url, http.StatusSeeOther)
}
return v
}
// RedirectView returns a View that redirects to the given URL
func (r *PageRequest) RedirectView(url string, opts ...ViewOption) *View {
return RedirectView(r.Request, url, opts...)
}
// CopyView returns a View that copies the content of a http.Response
func CopyView(resp *http.Response, opts ...ViewOption) *View {
v := &View{
StatusCode: resp.StatusCode,
Data: resp,
}
for _, opt := range opts {
opt(v)
}
bytes, _ := ioutil.ReadAll(resp.Body)
v.renderer = func(w http.ResponseWriter) {
for k, v := range resp.Header {
w.Header().Set(k, v[0])
}
w.WriteHeader(v.StatusCode)
w.Write(bytes)
}
return v
}
// CopyView returns a View that copies the content of a http.Response
func (r *PageRequest) CopyView(resp *http.Response, opts ...ViewOption) *View {
return CopyView(resp, opts...)
}
// AsyncCopyView returns a View that copies the content of a http.Response asynchronously
func AsyncCopyView(resp *http.Response, opts ...ViewOption) *View {
v := &View{
StatusCode: resp.StatusCode,
Data: resp,
closer: resp.Body.Close,
}
for _, opt := range opts {
opt(v)
}
v.renderer = func(w http.ResponseWriter) {
for k, v := range resp.Header {
w.Header().Set(k, v[0])
}
w.WriteHeader(v.StatusCode)
io.Copy(w, resp.Body)
}
return v
}
// AsyncCopyView returns a View that copies the content of a http.Response asynchronously
func (r *PageRequest) AsyncCopyView(resp *http.Response, opts ...ViewOption) *View {
return AsyncCopyView(resp, opts...)
}
// HandlerView returns a View that uses a http.HandlerFunc to render a response
func HandlerView(r *http.Request, handler http.HandlerFunc, opts ...ViewOption) *View {
v := &View{
StatusCode: http.StatusOK,
}
for _, opt := range opts {
opt(v)
}
v.renderer = func(w http.ResponseWriter) {
handler(w, r)
}
return v
}
// HandlerView returns a View that uses a http.HandlerFunc to render a response
func (r *PageRequest) HandlerView(handler http.HandlerFunc, opts ...ViewOption) *View {
return HandlerView(r.Request, handler, opts...)
}
// FileView returns a View that serves a file
func FileView(r *http.Request, file http.File, mime string, attachment bool, opts ...ViewOption) *View {
v := &View{
StatusCode: http.StatusOK,
closer: file.Close,
}
for _, opt := range opts {
opt(v)
}
fi, err := file.Stat()
if err != nil {
v.Error = err
v.renderer = func(w http.ResponseWriter) {
defaultErrorRenderer(w, r, err.Error(), http.StatusInternalServerError)
}
return v
}
v.renderer = func(w http.ResponseWriter) {
if attachment {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fi.Name()))
}
if len(mime) > 0 {
w.Header().Set("Content-Type", mime)
}
http.ServeContent(w, r, fi.Name(), fi.ModTime(), file)
}
return v
}
// FileView returns a View that serves a file
func (r *PageRequest) FileView(file http.File, mime string, attachment bool, opts ...ViewOption) *View {
return FileView(r.Request, file, mime, attachment, opts...)
}