-
Notifications
You must be signed in to change notification settings - Fork 11
/
context_x_response.go
344 lines (318 loc) · 8.64 KB
/
context_x_response.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package echo
import (
"bytes"
"encoding/xml"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"unicode"
"github.com/webx-top/echo/encoding/json"
"github.com/webx-top/echo/engine"
"github.com/webx-top/poolx/bufferpool"
)
// Response returns *Response.
func (c *xContext) Response() engine.Response {
return c.response
}
// Render renders a template with data and sends a text/html response with status
// code. Templates can be registered using `Echo.SetRenderer()`.
func (c *xContext) Render(name string, data interface{}, codes ...int) (err error) {
if c.auto {
if ok, err := c.echo.AutoDetectRenderFormat(c, data); ok {
return err
}
}
c.dataEngine.SetTmplFuncs()
if data == nil {
data = c.dataEngine.GetData()
}
b, err := c.Fetch(name, data)
if err != nil {
return
}
b = bytes.TrimLeftFunc(b, unicode.IsSpace)
c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
err = c.Blob(b, codes...)
return
}
func (c *xContext) RenderBy(name string, content func(string) ([]byte, error), data interface{}, codes ...int) (b []byte, err error) {
c.dataEngine.SetTmplFuncs()
if data == nil {
data = c.dataEngine.GetData()
}
if c.renderer == nil {
if c.echo.renderer == nil {
return nil, ErrRendererNotRegistered
}
c.renderer = c.echo.renderer
}
buf := bufferpool.Get()
defer bufferpool.Release(buf)
if c.renderDataWrapper != nil {
data = c.renderDataWrapper(c, data)
}
err = c.renderer.RenderBy(buf, name, content, data, c)
if err != nil {
return
}
b = buf.Bytes()
return
}
// HTML sends an HTTP response with status code.
func (c *xContext) HTML(html string, codes ...int) (err error) {
c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
err = c.Blob([]byte(html), codes...)
return
}
// String sends a string response with status code.
func (c *xContext) String(s string, codes ...int) (err error) {
c.response.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
err = c.Blob([]byte(s), codes...)
return
}
func (c *xContext) Blob(b []byte, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
err = c.preResponse()
if err != nil {
return
}
c.response.WriteHeader(c.code)
_, err = c.response.Write(b)
return
}
// JSON sends a JSON response with status code.
func (c *xContext) JSON(i interface{}, codes ...int) (err error) {
var b []byte
if c.echo.Debug() {
b, err = json.MarshalIndent(i, "", " ")
} else {
b, err = json.Marshal(i)
}
if err != nil {
return err
}
return c.JSONBlob(b, codes...)
}
// JSONBlob sends a JSON blob response with status code.
func (c *xContext) JSONBlob(b []byte, codes ...int) (err error) {
c.response.Header().Set(HeaderContentType, MIMEApplicationJSONCharsetUTF8)
err = c.Blob(b, codes...)
return
}
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
func (c *xContext) JSONP(callback string, i interface{}, codes ...int) (err error) {
b, err := json.Marshal(i)
if err != nil {
return err
}
c.response.Header().Set(HeaderContentType, MIMEApplicationJavaScriptCharsetUTF8)
b = []byte(callback + "(" + string(b) + ");")
err = c.Blob(b, codes...)
return
}
// XML sends an XML response with status code.
func (c *xContext) XML(i interface{}, codes ...int) (err error) {
var b []byte
if c.echo.Debug() {
b, err = xml.MarshalIndent(i, "", " ")
} else {
b, err = xml.Marshal(i)
}
if err != nil {
return err
}
return c.XMLBlob(b, codes...)
}
// XMLBlob sends a XML blob response with status code.
func (c *xContext) XMLBlob(b []byte, codes ...int) (err error) {
c.response.Header().Set(HeaderContentType, MIMEApplicationXMLCharsetUTF8)
b = []byte(xml.Header + string(b))
err = c.Blob(b, codes...)
return
}
func (c *xContext) Stream(step func(w io.Writer) bool) error {
return c.response.Stream(step)
}
func (c *xContext) SSEvent(event string, data chan interface{}) (err error) {
hdr := c.response.Header()
hdr.Set(HeaderContentType, MIMEEventStream)
hdr.Set(HeaderCacheControl, `no-cache`)
hdr.Set(HeaderConnection, `keep-alive`)
hdr.Set(HeaderTransferEncoding, `chunked`)
err = c.Stream(func(w io.Writer) bool {
recv, ok := <-data
if !ok {
return ok
}
b, _err := c.Fetch(event, recv)
if _err != nil {
err = _err
return false
}
//c.Logger().Debugf(`SSEvent: %s`, b)
_, _err = w.Write(b)
if _err != nil {
err = _err
return false
}
return true
})
return
}
func (c *xContext) Attachment(r io.Reader, name string, modtime time.Time, inline ...bool) error {
SetAttachmentHeader(c, name, true, inline...)
return c.ServeContent(r, name, modtime)
}
func (c *xContext) CacheableAttachment(r io.Reader, name string, modtime time.Time, maxAge time.Duration, inline ...bool) error {
SetAttachmentHeader(c, name, true, inline...)
return c.ServeContent(r, name, modtime, maxAge)
}
func (c *xContext) File(file string, fs ...http.FileSystem) error {
return c.CacheableFile(file, 0, fs...)
}
func (c *xContext) CacheableFile(file string, maxAge time.Duration, fs ...http.FileSystem) (err error) {
var f http.File
customFS := len(fs) > 0 && fs[0] != nil
if customFS {
f, err = fs[0].Open(file)
} else {
f, err = os.Open(file)
}
if err != nil {
return ErrNotFound
}
defer func() {
if f != nil {
f.Close()
}
}()
fi, err := f.Stat()
if err != nil {
return err
}
if fi.IsDir() {
f.Close()
file = filepath.Join(file, "index.html")
if customFS {
f, err = fs[0].Open(file)
} else {
f, err = os.Open(file)
}
if err != nil {
return ErrNotFound
}
fi, err = f.Stat()
if err != nil {
return err
}
}
if maxAge > time.Second {
if c.IsValidCache(fi.ModTime()) {
return c.NotModified()
}
c.SetCacheHeader(fi.ModTime(), maxAge)
}
c.Response().ServeContent(f, fi.Name(), fi.ModTime())
return nil
}
func (c *xContext) ServeContent(content io.Reader, name string, modtime time.Time, cacheMaxAge ...time.Duration) error {
if readSeeker, ok := content.(io.ReadSeeker); ok {
if c.IsValidCache(modtime) {
return c.NotModified()
}
c.SetCacheHeader(modtime, cacheMaxAge...)
c.Response().ServeContent(readSeeker, name, modtime)
return nil
}
return c.ServeCallbackContent(func(_ Context) (io.Reader, error) {
return content, nil
}, name, modtime)
}
func (c *xContext) IsValidCache(modifiedAt time.Time) bool {
t, err := time.Parse(http.TimeFormat, c.Request().Header().Get(HeaderIfModifiedSince))
return err == nil && modifiedAt.Before(t.Add(1*time.Second))
}
func (c *xContext) SetCacheHeader(modifiedAt time.Time, maxAge ...time.Duration) {
rs := c.Response()
hdr := rs.Header()
if len(maxAge) > 0 && maxAge[0] > time.Second {
now := time.Now().UTC()
expiredAt := now.Add(maxAge[0])
hdr.Set(HeaderExpires, expiredAt.Format(http.TimeFormat))
hdr.Set(HeaderCacheControl, CacheControlPrefix+strconv.Itoa(int(maxAge[0].Seconds())))
}
hdr.Set(HeaderLastModified, modifiedAt.UTC().Format(http.TimeFormat))
}
func (c *xContext) NotModified() error {
rs := c.Response()
rs.Header().Del(HeaderContentType)
rs.Header().Del(HeaderContentLength)
return c.NoContent(http.StatusNotModified)
}
func (c *xContext) ServeCallbackContent(callback func(Context) (io.Reader, error), name string, modtime time.Time, cacheMaxAge ...time.Duration) error {
if c.IsValidCache(modtime) {
return c.NotModified()
}
content, err := callback(c)
if err != nil {
return err
}
if readSeeker, ok := content.(io.ReadSeeker); ok {
c.SetCacheHeader(modtime, cacheMaxAge...)
c.Response().ServeContent(readSeeker, name, modtime)
return nil
}
rs := c.Response()
rs.Header().Set(HeaderContentType, ContentTypeByExtension(name))
c.SetCacheHeader(modtime, cacheMaxAge...)
rs.WriteHeader(http.StatusOK)
rs.KeepBody(false)
_, err = io.Copy(rs, content)
return err
}
// NoContent sends a response with no body and a status code.
func (c *xContext) NoContent(codes ...int) error {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.WriteHeader(c.code)
return nil
}
// Redirect redirects the request with status code.
func (c *xContext) Redirect(url string, codes ...int) error {
code := http.StatusFound
if len(codes) > 0 {
code = codes[0]
}
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return ErrInvalidRedirectCode
}
err := c.preResponse()
if err != nil {
return err
}
format := c.Format()
if format != `html` && c.auto {
if render, ok := c.echo.formatRenderers[format]; ok && render != nil {
if c.dataEngine.GetData() == nil {
c.dataEngine.SetData(c.Stored(), c.dataEngine.GetCode().Int())
}
c.dataEngine.SetURL(url)
return render(c, c.dataEngine.GetData())
}
}
c.response.Redirect(url, code)
return nil
}