/
response.go
215 lines (188 loc) · 5.89 KB
/
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
package air
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
)
// Response represents the current HTTP response.
//
// It's embedded with the `http.ResponseWriter`, the `http.Hijacker`, the `http.CloseNotifier`,
// the `http.Flusher` and the `http.Pusher`.
type Response struct {
http.ResponseWriter
http.Hijacker
http.CloseNotifier
http.Flusher
http.Pusher
context *Context
StatusCode int
Size int
Written bool
Data Map
}
// NewResponse returns a pointer of a new instance of the `Response`.
func NewResponse(c *Context) *Response {
return &Response{
context: c,
StatusCode: http.StatusOK,
Data: make(Map),
}
}
// Write implements the `http.ResponseWriter#Write()`.
func (r *Response) Write(b []byte) (int, error) {
if !r.Written {
r.WriteHeader(r.StatusCode)
}
n, err := r.ResponseWriter.Write(b)
r.Size += n
return n, err
}
// WriteHeader implements the `http.ResponseWriter#WriteHeader()`.
func (r *Response) WriteHeader(statusCode int) {
if r.Written {
r.context.Air.Logger.Warn("response already written")
return
}
r.ResponseWriter.WriteHeader(statusCode)
r.StatusCode = statusCode
r.Written = true
}
// SetCookie adds a "Set-Cookie" header in the r. The provided cookie must have a valid `Name`.
// Invalid cookies may be silently dropped.
func (r *Response) SetCookie(cookie *http.Cookie) {
http.SetCookie(r, cookie)
}
// Render renders one or more HTML templates with the `Data` of the r and sends a "text/html" HTTP
// response. The default `Renderer` does it by using the `template.Template`. the rults rendered by
// the former can be inherited by accessing the `Data["InheritedHTML"]` of the r.
func (r *Response) Render(templates ...string) error {
buf := &bytes.Buffer{}
for _, t := range templates {
r.Data["InheritedHTML"] = template.HTML(buf.Bytes())
buf.Reset()
if err := r.context.Air.Renderer.Render(buf, t, r.Data); err != nil {
return err
}
}
return r.Blob(MIMETextHTML+CharsetUTF8, buf.Bytes())
}
// HTML sends a "text/html" HTTP response with the html.
func (r *Response) HTML(html string) error {
return r.Blob(MIMETextHTML+CharsetUTF8, []byte(html))
}
// String sends a "text/plain" HTTP response with the s.
func (r *Response) String(s string) error {
return r.Blob(MIMETextPlain+CharsetUTF8, []byte(s))
}
// JSON sends an "application/json" HTTP response with the type i.
func (r *Response) JSON(i interface{}) error {
b, err := json.Marshal(i)
if r.context.Air.Config.DebugMode {
b, err = json.MarshalIndent(i, "", "\t")
}
if err != nil {
return err
}
return r.Blob(MIMEApplicationJSON+CharsetUTF8, b)
}
// JSONP sends an "application/javascript" HTTP response with the type i. It uses the callback to
// construct the JSONP payload.
func (r *Response) JSONP(i interface{}, callback string) error {
b, err := json.Marshal(i)
if err != nil {
return err
}
b = append([]byte(callback+"("), b...)
b = append(b, []byte(");")...)
return r.Blob(MIMEApplicationJavaScript+CharsetUTF8, b)
}
// XML sends an "application/xml" HTTP response with the type i.
func (r *Response) XML(i interface{}) error {
b, err := xml.Marshal(i)
if r.context.Air.Config.DebugMode {
b, err = xml.MarshalIndent(i, "", "\t")
}
if err != nil {
return err
}
return r.Blob(MIMEApplicationXML+CharsetUTF8, append([]byte(xml.Header), b...))
}
// Blob sends a blob HTTP response with the contentType and the b.
func (r *Response) Blob(contentType string, b []byte) error {
r.Header().Set(HeaderContentType, contentType)
_, err := r.Write(b)
return err
}
// Stream sends a streaming HTTP response with the contentType and the reader.
func (r *Response) Stream(contentType string, reader io.Reader) error {
r.Header().Set(HeaderContentType, contentType)
_, err := io.Copy(r, reader)
return err
}
// File sends a file HTTP response with the file.
func (r *Response) File(file string) error {
if _, err := os.Stat(file); os.IsNotExist(err) {
return ErrNotFound
}
abs, err := filepath.Abs(file)
if err != nil {
return err
}
if a := r.context.Air.Coffer.Asset(abs); a != nil {
http.ServeContent(r, r.context.Request.Request, a.Name(), a.ModTime(), a)
} else {
http.ServeFile(r, r.context.Request.Request, abs)
}
return nil
}
// Attachment sends an HTTP response with the file and the filename as attachment, prompting client
// to save the file.
func (r *Response) Attachment(file, filename string) error {
return r.contentDisposition("attachment", file, filename)
}
// Inline sends an HTTP response with the file and the filename as inline, opening the file in the
// browser.
func (r *Response) Inline(file, filename string) error {
return r.contentDisposition("inline", file, filename)
}
// contentDisposition sends an HTTP response with the file and the filename as the dispositionType.
func (r *Response) contentDisposition(dispositionType, file, filename string) error {
r.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s",
dispositionType, filename))
return r.File(file)
}
// NoContent sends an HTTP response with no body.
func (r *Response) NoContent() error { return nil }
// Redirect redirects the current HTTP request to the url with the statusCode.
func (r *Response) Redirect(statusCode int, url string) error {
if statusCode < http.StatusMultipleChoices || statusCode > http.StatusTemporaryRedirect {
return ErrInvalidRedirectCode
}
r.Header().Set(HeaderLocation, url)
r.WriteHeader(statusCode)
return nil
}
// feed feeds the rw into where it should be.
func (r *Response) feed(rw http.ResponseWriter) {
r.ResponseWriter = rw
r.Hijacker, _ = rw.(http.Hijacker)
r.CloseNotifier, _ = rw.(http.CloseNotifier)
r.Flusher, _ = rw.(http.Flusher)
r.Pusher, _ = rw.(http.Pusher)
}
// reset resets all fields in the r.
func (r *Response) reset() {
r.ResponseWriter = nil
r.StatusCode = http.StatusOK
r.Size = 0
r.Written = false
for k := range r.Data {
delete(r.Data, k)
}
}