-
Notifications
You must be signed in to change notification settings - Fork 251
/
context_output.go
376 lines (334 loc) · 10.6 KB
/
context_output.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Copyright 2022 AndeyaLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package faygo
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"path/filepath"
"strconv"
"strings"
"time"
"unsafe"
"github.com/andeya/faygo/acceptencoder"
)
// Size returns the current size, in bytes, of the response.
func (ctx *Context) Size() int64 {
return ctx.W.Size()
}
// Committed returns whether the response has been submitted or not.
func (ctx *Context) Committed() bool {
return ctx.W.committed
}
// Status returns the HTTP status code of the response.
func (ctx *Context) Status() int {
return ctx.W.status
}
// IsCachable returns boolean of this request is cached.
// HTTP 304 means cached.
func (ctx *Context) IsCachable() bool {
return ctx.W.status >= 200 && ctx.W.status < 300 || ctx.W.status == 304
}
// IsEmpty returns boolean of this request is empty.
// HTTP 201,204 and 304 means empty.
func (ctx *Context) IsEmpty() bool {
return ctx.W.status == 201 || ctx.W.status == 204 || ctx.W.status == 304
}
// IsOk returns boolean of this request runs well.
// HTTP 200 means ok.
func (ctx *Context) IsOk() bool {
return ctx.W.status == 200
}
// IsSuccessful returns boolean of this request runs successfully.
// HTTP 2xx means ok.
func (ctx *Context) IsSuccessful() bool {
return ctx.W.status >= 200 && ctx.W.status < 300
}
// IsRedirect returns boolean of this request is redirection header.
// HTTP 301,302,307 means redirection.
func (ctx *Context) IsRedirect() bool {
return ctx.W.status == 301 || ctx.W.status == 302 || ctx.W.status == 303 || ctx.W.status == 307
}
// IsForbidden returns boolean of this request is forbidden.
// HTTP 403 means forbidden.
func (ctx *Context) IsForbidden() bool {
return ctx.W.status == 403
}
// IsNotFound returns boolean of this request is not found.
// HTTP 404 means forbidden.
func (ctx *Context) IsNotFound() bool {
return ctx.W.status == 404
}
// IsClientError returns boolean of this request client sends error data.
// HTTP 4xx means forbidden.
func (ctx *Context) IsClientError() bool {
return ctx.W.status >= 400 && ctx.W.status < 500
}
// IsServerError returns boolean of this server handler errors.
// HTTP 5xx means server internal error.
func (ctx *Context) IsServerError() bool {
return ctx.W.status >= 500 && ctx.W.status < 600
}
// SetHeader sets response header item string via given key.
func (ctx *Context) SetHeader(key, val string) {
ctx.W.Header().Set(key, val)
}
// SetCookie sets cookie value via given key.
// others are ordered as cookie's max age time, path, domain, secure and httponly.
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
var b bytes.Buffer
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
// fix cookie not work in IE
if len(others) > 0 {
var maxAge int64
switch v := others[0].(type) {
case int:
maxAge = int64(v)
case int32:
maxAge = int64(v)
case int64:
maxAge = v
}
switch {
case maxAge > 0:
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(maxAge)*time.Second).UTC().Format(time.RFC1123), maxAge)
case maxAge < 0:
fmt.Fprintf(&b, "; Max-Age=0")
}
}
// the settings below
// Path, Domain, Secure, HttpOnly
// can use nil skip set
// default "/"
if len(others) > 1 {
if v, ok := others[1].(string); ok && len(v) > 0 {
fmt.Fprintf(&b, "; Path=%s", sanitizeValue(v))
}
} else {
fmt.Fprintf(&b, "; Path=%s", "/")
}
// default empty
if len(others) > 2 {
if v, ok := others[2].(string); ok && len(v) > 0 {
fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(v))
}
}
// default empty
if len(others) > 3 {
var secure bool
switch v := others[3].(type) {
case bool:
secure = v
default:
if others[3] != nil {
secure = true
}
}
if secure {
fmt.Fprintf(&b, "; Secure")
}
}
// default false. for session cookie default true
httponly := false
if len(others) > 4 {
if v, ok := others[4].(bool); ok && v {
// HttpOnly = true
httponly = true
}
}
if httponly {
fmt.Fprintf(&b, "; HttpOnly")
}
ctx.W.Header().Add(HeaderSetCookie, b.String())
}
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
func sanitizeName(n string) string {
return cookieNameSanitizer.Replace(n)
}
var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ")
func sanitizeValue(v string) string {
return cookieValueSanitizer.Replace(v)
}
// SetSecureCookie Set Secure cookie for response.
func (ctx *Context) SetSecureCookie(secret, name, value string, others ...interface{}) {
vs := base64.URLEncoding.EncodeToString([]byte(value))
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
h := hmac.New(sha1.New, []byte(secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
sig := fmt.Sprintf("%02x", h.Sum(nil))
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
ctx.SetCookie(name, cookie, others...)
}
// NoContent sends a response with no body and a status code.
func (ctx *Context) NoContent(status int) {
ctx.W.WriteHeader(status)
}
// Send error message and stop handler chain.
func (ctx *Context) Error(status int, errStr string) {
global.errorFunc(ctx, errStr, status)
ctx.Stop()
}
// Bytes writes the data bytes to the connection as part of an HTTP reply.
func (ctx *Context) Bytes(status int, contentType string, content []byte) error {
if ctx.W.committed {
ctx.W.multiCommitted()
return nil
}
ctx.W.Header().Set(HeaderContentType, contentType)
if ctx.enableGzip && len(ctx.W.Header()[HeaderContentEncoding]) == 0 {
buf := &bytes.Buffer{}
ok, encoding, _ := acceptencoder.WriteBody(acceptencoder.ParseEncoding(ctx.R), buf, content)
if ok {
ctx.W.Header().Set(HeaderContentEncoding, encoding)
content = buf.Bytes()
}
}
ctx.W.Header().Set(HeaderContentLength, strconv.Itoa(len(content)))
ctx.W.WriteHeader(status)
_, err := ctx.W.Write(content)
return err
}
// String writes a string to the client, something like fmt.Fprintf
func (ctx *Context) String(status int, format string, s ...interface{}) error {
if len(s) == 0 {
return ctx.Bytes(status, MIMETextPlainCharsetUTF8, []byte(format))
}
return ctx.Bytes(status, MIMETextPlainCharsetUTF8, []byte(fmt.Sprintf(format, s...)))
}
// HTML sends an HTTP response with status code.
func (ctx *Context) HTML(status int, html string) error {
x := (*[2]uintptr)(unsafe.Pointer(&html))
h := [3]uintptr{x[0], x[1], x[1]}
return ctx.Bytes(status, MIMETextHTMLCharsetUTF8, *(*[]byte)(unsafe.Pointer(&h)))
}
// JSON sends a JSON response with status code.
func (ctx *Context) JSON(status int, data interface{}, isIndent ...bool) error {
var (
b []byte
err error
)
if len(isIndent) > 0 && isIndent[0] {
b, err = json.MarshalIndent(data, "", " ")
} else {
b, err = json.Marshal(data)
}
if err != nil {
return err
}
return ctx.JSONBlob(status, b)
}
// JSONBlob sends a JSON blob response with status code.
func (ctx *Context) JSONBlob(status int, b []byte) error {
return ctx.Bytes(status, MIMEApplicationJSONCharsetUTF8, b)
}
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
func (ctx *Context) JSONP(status int, callback string, data interface{}, isIndent ...bool) error {
var (
b []byte
err error
)
if len(isIndent) > 0 && isIndent[0] {
b, err = json.MarshalIndent(data, "", " ")
} else {
b, err = json.Marshal(data)
}
if err != nil {
return err
}
callback = template.JSEscapeString(callback)
callbackContent := bytes.NewBufferString(" if(window." + callback + ")" + callback)
callbackContent.WriteString("(")
callbackContent.Write(b)
callbackContent.WriteString(");\r\n")
return ctx.Bytes(status, MIMEApplicationJavaScriptCharsetUTF8, callbackContent.Bytes())
}
// JSONMsg sends a JSON with JSONMsg format.
func (ctx *Context) JSONMsg(status int, msgcode int, info interface{}, isIndent ...bool) error {
var (
b []byte
err error
data = JSONMsg{
Code: msgcode,
Info: info,
}
)
if len(isIndent) > 0 && isIndent[0] {
b, err = json.MarshalIndent(data, "", " ")
} else {
b, err = json.Marshal(data)
}
if err != nil {
return err
}
return ctx.JSONBlob(status, b)
}
// XML sends an XML response with status code.
func (ctx *Context) XML(status int, data interface{}, isIndent ...bool) error {
var (
b []byte
err error
)
if len(isIndent) > 0 && isIndent[0] {
b, err = xml.MarshalIndent(data, "", " ")
} else {
b, err = xml.Marshal(data)
}
if err != nil {
return err
}
return ctx.XMLBlob(status, b)
}
// XMLBlob sends a XML blob response with status code.
func (ctx *Context) XMLBlob(status int, b []byte) error {
content := bytes.NewBufferString(xml.Header)
content.Write(b)
return ctx.Bytes(status, MIMEApplicationXMLCharsetUTF8, content.Bytes())
}
// JSONOrXML serve Xml OR Json, depending on the value of the Accept header
func (ctx *Context) JSONOrXML(status int, data interface{}, isIndent ...bool) error {
if ctx.AcceptJSON() || !ctx.AcceptXML() {
return ctx.JSON(status, data, isIndent...)
}
return ctx.XML(status, data, isIndent...)
}
// File forces response for download file.
// it prepares the download response header automatically.
func (ctx *Context) File(localFilename string, showFilename ...string) {
ctx.W.Header().Set(HeaderContentDescription, "File Transfer")
ctx.W.Header().Set(HeaderContentType, MIMEOctetStream)
if len(showFilename) > 0 && showFilename[0] != "" {
ctx.W.Header().Set(HeaderContentDisposition, "attachment; filename="+showFilename[0])
} else {
ctx.W.Header().Set(HeaderContentDisposition, "attachment; filename="+filepath.Base(localFilename))
}
ctx.W.Header().Set(HeaderContentTransferEncoding, "binary")
ctx.W.Header().Set(HeaderExpires, "0")
ctx.W.Header().Set(HeaderCacheControl, "must-revalidate")
ctx.W.Header().Set(HeaderPragma, "public")
global.fsManager.ServeFile(ctx, localFilename)
}
// Render renders a template with data and sends a text/html response with status code.
func (ctx *Context) Render(status int, name string, data Map) error {
b, err := global.render.Render(name, data)
if err != nil {
return err
}
return ctx.Bytes(status, MIMETextHTMLCharsetUTF8, b)
}