-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
544 lines (482 loc) · 13 KB
/
context.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package web
import (
"encoding/json"
"encoding/xml"
"fmt"
"log"
"mime/multipart"
"net/http"
"net/url"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/gorilla/schema"
"github.com/valyala/fasthttp"
)
// Ctx web context
type Ctx struct {
*Core
*fasthttp.RequestCtx
*Route
index int
method string
path string
values []string
err error
}
// Cookie struct
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
Secure bool
HTTPOnly bool
SameSite string
}
var (
schemaDecoderForm = schema.NewDecoder()
schemaDecoderQuery = schema.NewDecoder()
cacheControlNoCacheRegexp, _ = regexp.Compile(`/(?:^|,)\s*?no-cache\s*?(?:,|$)/`)
poolCtx = sync.Pool{
New: func() interface{} { return new(Ctx) },
}
)
func assignCtx(fctx *fasthttp.RequestCtx) *Ctx {
c := poolCtx.Get().(*Ctx)
c.index = -1
c.path = getString(fctx.URI().Path())
c.method = getString(fctx.Request.Header.Method())
c.RequestCtx = fctx
return c
}
func releaseCtx(c *Ctx) {
c.Route = nil
c.values = nil
c.RequestCtx = nil
c.err = nil
poolCtx.Put(c)
}
// Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
func (ctx *Ctx) Method(override ...string) string {
if len(override) > 0 {
method := strings.ToUpper(override[0])
if methodINT[method] == 0 && method != MethodGet {
log.Fatalf("Method: Invalid HTTP method override %s", method)
}
ctx.method = method
}
return ctx.method
}
// View 显示模版
func (c *Ctx) View(filename string, optionalViewModel ...interface{}) error {
c.Set(HeaderContentType, MIMETextHTML)
var binding interface{}
if len(optionalViewModel) > 0 {
binding = optionalViewModel[0]
} else {
binds := make(map[string]interface{})
// 遍历用户变量 注入模版引擎中.
c.VisitUserValues(func(k []byte, v interface{}) {
binds[getString(k)] = v
})
binding = binds
}
err := c.Core.View(c.RequestCtx.Response.BodyWriter(), filename, "", binding)
if err != nil {
c.SendStatus(500)
}
return err
}
// Render 直接渲染不渲染 layout
func (c *Ctx) Render(filename string, optionalViewModel ...interface{}) error {
c.Set(HeaderContentType, MIMETextHTML)
var binding interface{}
if len(optionalViewModel) > 0 {
binding = optionalViewModel[0]
} else {
binds := make(map[string]interface{})
// 遍历用户变量 注入模版引擎中.
c.VisitUserValues(func(k []byte, v interface{}) {
binds[getString(k)] = v
})
binding = binds
}
err := c.Core.View(c.RequestCtx.Response.BodyWriter(), filename, "nolayout", binding)
if err != nil {
c.SendStatus(500)
}
return err
}
// Vars 本地数据
func (c *Ctx) Vars(k string, v ...interface{}) (val interface{}) {
if len(v) == 0 { // read
return c.UserValue(k)
}
c.SetUserValue(k, v[0])
return v[0]
}
// Query returns the query string parameter in the url.
func (c *Ctx) Query(k string) (value string) {
return getString(c.QueryArgs().Peek(k))
}
// Set ctx set header
func (c *Ctx) Set(k, v string) {
c.Response.Header.Set(k, v)
}
// Get the http request header specified by field
func (c *Ctx) Get(k string) string {
if k == "referrer" {
k = "referer"
}
return getString(c.Request.Header.Peek(k))
}
// Path 返回path
func (c *Ctx) Path() string {
return c.path
}
// Redirect 页面跳转
func (c *Ctx) Redirect(path string, status ...int) {
code := 302
if len(status) > 0 { // custom code
code = status[0]
}
c.Set("Location", path)
c.Response.SetStatusCode(code)
}
// SaveFile saves any multipart file to disk.
func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
return fasthttp.SaveMultipartFile(fileheader, path)
}
// SendStatus 发送 http code
func (c *Ctx) SendStatus(code int) {
c.Response.SetStatusCode(code)
if len(c.Response.Body()) == 0 {
c.Response.SetBodyString(statusMessages[code])
}
}
// SendFile transfers the from the give path.
func (c *Ctx) SendFile(file string, noCompression ...bool) {
if len(noCompression) > 0 && noCompression[0] {
fasthttp.ServeFileUncompressed(c.RequestCtx, file)
return
}
fasthttp.ServeFile(c.RequestCtx, file)
}
// Send sets the HTTP response body. The Send body can be of any type.
func (c *Ctx) Send(bodies ...interface{}) {
if len(bodies) > 0 {
c.Response.SetBodyString("")
}
c.Write(bodies...)
}
// Write appends any input to the HTTP body response.
func (c *Ctx) Write(bodies ...interface{}) {
for i := range bodies {
switch body := bodies[i].(type) {
case string:
c.Response.AppendBodyString(body)
case []byte:
c.Response.AppendBodyString(getString(body))
default:
c.Response.AppendBodyString(fmt.Sprintf("%v", body))
}
}
}
// Params is used to get the route parameters.
func (c *Ctx) Params(k string) (v string) {
if c.Route.Params == nil {
return
}
for i := 0; i < len(c.Route.Params); i++ {
if (c.Route.Params)[i] == k {
return c.values[i]
}
}
return
}
// Next 执行下一个操作
func (c *Ctx) Next(err ...error) {
c.Route = nil
c.values = nil
if len(err) > 0 {
c.err = err[0]
return
}
c.nextRoute(c)
}
// Router returns the matched Route struct.
func (c *Ctx) Router() *Route {
if c.Route == nil {
// Fallback for fasthttp error handler
return &Route{
Path: c.path,
Method: c.method,
Handlers: make([]Handler, 0),
}
}
return c.Route
}
// Fresh When the response is still “fresh” in the client’s cache true is returned,
// otherwise false is returned to indicate that the client cache is now stale
// and the full response should be sent.
// When a client sends the Cache-Control: no-cache request header to indicate an end-to-end
// reload request, this module will return false to make handling these requests transparent.
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
func (c *Ctx) Fresh() bool {
modifiedSince := c.Get(HeaderIfModifiedSince)
noneMath := c.Get(HeaderIfNoneMatch)
if modifiedSince == "" && noneMath == "" {
return false
}
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
cacheControl := c.Get(HeaderCacheControl)
if cacheControl != "" && cacheControlNoCacheRegexp.MatchString(cacheControl) {
return false
}
// if-none-match
if noneMath != "" && noneMath != "*" {
etag := getString(c.Response.Header.Peek(HeaderETag))
if etag == "" {
return false
}
etagStal := true
matches := parseTokenList(getBytes(noneMath))
for i := range matches {
match := matches[i]
if match == etag || match == "W/"+etag || "W/"+match == etag {
etagStal = false
break
}
}
if etagStal {
return false
}
if modifiedSince != "" {
lastModified := getString(c.Response.Header.Peek(HeaderLastModified))
if lastModified != "" {
lastModifiedTime, err := http.ParseTime(lastModified)
if err != nil {
return false
}
modifiedSinceTime, err := http.ParseTime(modifiedSince)
if err != nil {
return false
}
return lastModifiedTime.Before(modifiedSinceTime)
}
}
}
return true
}
// Host contains the hostname derived from the Host HTTP header.
func (c Ctx) Host() string {
return getString(c.URI().Host())
}
// IP returns the remote IP address of the request.
func (c *Ctx) IP() string {
ip := c.Get("X-Real-IP")
if ip != "" {
return ip
}
ip = strings.Join(c.IPs(), ",")
if ip != "" {
return ip
}
return c.RemoteIP().String()
}
// IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.
func (c *Ctx) IPs() []string {
ips := strings.Split(c.Get(HeaderXForwardedFor), ",")
for i := range ips {
ips[i] = strings.TrimSpace(ips[i])
}
return ips
}
// JSON 发送 json 数据
func (c *Ctx) JSON(data interface{}) error {
raw, err := json.Marshal(&data)
if err != nil {
return err
}
c.Response.Header.SetContentType(MIMEApplicationJSON)
c.Response.SetBodyString(getString(raw))
return nil
}
// ToJSON 返回js数据处理错误
func (c *Ctx) ToJSON(data interface{}, err error) error {
if err != nil {
return c.JSON(map[string]interface{}{
"status": false,
"result": data,
"msg": err.Error(),
})
}
return c.JSON(map[string]interface{}{
"status": true,
"result": data,
"msg": "success",
})
}
// JSONP 发送jsonp 数据
func (c *Ctx) JSONP(data interface{}, callback ...string) error {
raw, err := json.Marshal(&data)
if err != nil {
return err
}
str := "callback("
if len(callback) > 0 {
str = callback[0] + "("
}
str += getString(raw) + ");"
c.Set(HeaderXContentTypeOptions, "nosniff")
c.Response.Header.SetContentType(MIMEApplicationJavaScript)
c.Response.SetBodyString(str)
return nil
}
// FormValue 读取 form的值
func (c *Ctx) FormValue(k string) (v string) {
return getString(c.RequestCtx.FormValue(k))
}
// FormFile returns the first file by key from a MultipartForm.
// func (c *Ctx) FormFile(k string) (*multipart.FileHeader, error) {
// return c.RequestCtx.FormFile(k)
// }
// Download transfers the file from path as an attachment.
// Typically, browsers will prompt the user for download.
// By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
// Override this default with the filename parameter.
func (c *Ctx) Download(file string, name ...string) {
filename := filepath.Base(file)
if len(name) > 0 { // 如果有指定名称
filename = name[0]
}
c.Set(HeaderContentDisposition, "attachment; filename="+filename)
c.SendFile(file)
}
// Cookies is used for getting a cookie value by key
func (c *Ctx) Cookies(key ...string) (value string) {
if len(key) == 0 {
fmt.Println("DEPRECATED: c.Cookies() without a key is deprecated, please use c.Get(\"Cookies\") to get the cookie header instead.")
return c.Get(HeaderCookie)
}
return getString(c.Request.Header.Cookie(key[0]))
}
// Cookie sets a cookie by passing a cookie struct
func (c *Ctx) Cookie(cookie *Cookie) {
fc := &fasthttp.Cookie{}
fc.SetKey(cookie.Name)
fc.SetValue(cookie.Value)
fc.SetPath(cookie.Path)
fc.SetDomain(cookie.Domain)
fc.SetExpire(cookie.Expires)
fc.SetSecure(cookie.Secure)
if cookie.Secure {
fc.SetSameSite(fasthttp.CookieSameSiteNoneMode)
}
fc.SetHTTPOnly(cookie.HTTPOnly)
switch strings.ToLower(cookie.SameSite) {
case "lax":
fc.SetSameSite(fasthttp.CookieSameSiteLaxMode)
case "strict":
fc.SetSameSite(fasthttp.CookieSameSiteStrictMode)
case "none":
fc.SetSameSite(fasthttp.CookieSameSiteNoneMode)
fc.SetSecure(true)
default:
fc.SetSameSite(fasthttp.CookieSameSiteDisabled)
}
c.Response.Header.SetCookie(fc)
}
// ClearCookie expires a specific cookie by key.
// If no key is provided it expires all cookies.
func (c *Ctx) ClearCookie(key ...string) {
if len(key) > 0 {
for i := range key {
c.Response.Header.DelClientCookie(key[i])
}
return
}
c.Request.Header.VisitAllCookie(func(k, v []byte) {
c.Response.Header.DelClientCookie(getString(k))
})
}
// Body contains the raw body submitted in a POST request.
// If a key is provided, it returns the form value 获得某个值用 c.FormValue
func (c *Ctx) Body() string {
return getString(c.Request.Body())
}
// Hostname host name
func (c *Ctx) Hostname() string {
return getString(c.URI().Host())
}
// ReadBody 读取body 数据
func (c *Ctx) ReadBody(out interface{}) error {
ctype := getString(c.Request.Header.ContentType())
switch {
// application/json text/plain
case strings.HasPrefix(ctype, MIMEApplicationJSON), strings.HasPrefix(ctype, MIMETextPlain):
return json.Unmarshal(c.Request.Body(), out)
// application/xml text/xml
case strings.HasPrefix(ctype, MIMEApplicationXML), strings.HasPrefix(ctype, MIMETextXML):
return xml.Unmarshal(c.Request.Body(), out)
// application/x-www-form-urlencoded
case strings.HasPrefix(ctype, MIMEApplicationForm):
data, err := url.ParseQuery(getString(c.PostBody()))
if err != nil {
return err
}
return schemaDecoderForm.Decode(out, data)
case c.QueryArgs().Len() > 0:
data := make(map[string][]string)
c.QueryArgs().VisitAll(func(k, v []byte) {
data[getString(k)] = append(data[getString(k)], getString(v))
})
return schemaDecoderQuery.Decode(out, data)
}
return fmt.Errorf("ReadBody: can not support content-type:%v", ctype)
}
// Subdomains 子域名.
func (c *Ctx) Subdomains(offset ...int) string {
o := 2
if len(offset) > 0 {
o = offset[0]
}
subdomains := strings.Split(c.Hostname(), ".")
l := len(subdomains) - o
if l < 0 {
l = len(subdomains)
}
return strings.Join(subdomains[:l], ".")
}
// Domain 返回域名
// 如果包含基础域名就返回二级域名
// 反之返回完整域名.
func (c *Ctx) Domain(bases []string) string {
host := c.Hostname()
for _, item := range bases {
if strings.HasSuffix(host, item) { // 包含了根域名
barr := strings.Split(item, ".")
return c.Subdomains(len(barr))
}
}
return host
}
// RootDomain 获取主域名 默认2位
func (c *Ctx) RootDomain(offset ...int) string {
o := 2
if len(offset) > 0 {
o = offset[0]
}
subdomains := strings.Split(c.Hostname(), ".")
l := len(subdomains) - o
if l < 0 {
l = 0
}
return strings.Join(subdomains[l:], ".")
}