-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcontext.go
794 lines (701 loc) · 20.4 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
// Package makross is a high productive and modular web framework in Golang.
package makross
import (
"bytes"
ktx "context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"mime"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/insionng/makross/libraries/i18n"
)
const (
indexPage = "index.html"
defaultMemory = 32 << 20 // 32 MB
)
type (
// Context represents the contextual data and environment while processing an incoming HTTP request.
Context struct {
Request *http.Request // the current request
Response *Response // the response writer
ktx ktx.Context // standard context
Localer
Flash *Flash
Session Sessioner
makross *Makross
pnames []string // list of route parameter names
pvalues []string // list of parameter values corresponding to pnames
data map[string]interface{} // data items managed by Get and Set
FiltersMap *sync.Map //map[string][]byte // Not Global Filters, only in Context
index int // the index of the currently executing handler in handlers
handlers []Handler // the handlers associated with the current route
writer DataWriter
}
// Localer reprents a localization interface.
Localer interface {
Language() string
Tr(string, ...interface{}) string
}
localer struct {
i18n.Locale
}
)
// Reset sets the request and response of the context and resets all other properties.
func (c *Context) Reset(w http.ResponseWriter, r *http.Request) {
c.Response.reset(w)
c.Request = r
c.ktx = ktx.Background()
c.data = nil
c.FiltersMap = new(sync.Map)
c.index = -1
c.writer = DefaultDataWriter
}
// NewContext creates a new Context object with the given response, request, and the handlers.
// This method is primarily provided for writing unit tests for handlers.
/*
func NewContext(w http.ResponseWriter, r *http.Request, handlers ...Handler) *Context {
//c := &Context{handlers: handlers}
m := New()
c := &Context{
Request: r,
Response: NewResponse(w, m),
makross: m,
pvalues: make([]string, m.maxParams),
handlers: handlers,
}
c.Reset(w, r)
return c
}
*/
// Makross returns the Makross that is handling the incoming HTTP request.
func (c *Context) Makross() *Makross {
return c.makross
}
// Shutdown 优雅停止HTTP服务 不超过特定时长
func (c *Context) Shutdown(times ...int64) error {
return c.makross.Shutdown(times...)
}
// Close 立即关闭HTTP服务
func (c *Context) Close() error {
return c.makross.Server.Close()
}
func (c *Context) Kontext() ktx.Context {
return c.ktx
}
func (c *Context) SetKontext(ktx ktx.Context) {
c.ktx = ktx
}
func (c *Context) Handler() Handler {
return c.handlers[c.index]
}
func (c *Context) SetHandler(h Handler) {
c.handlers[c.index] = h
}
func (c *Context) NewCookie() *http.Cookie {
return new(http.Cookie)
}
func (c *Context) GetCookie(name string) (*http.Cookie, error) {
return c.Request.Cookie(name)
}
func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response, cookie)
}
func (c *Context) GetCookies() []*http.Cookie {
return c.Request.Cookies()
}
// NewHTTPError creates a new HTTPError instance.
func (c *Context) NewHTTPError(status int, message ...interface{}) *HTTPError {
return c.makross.NewHTTPError(status, message...)
}
func (c *Context) Error(status int, message ...interface{}) {
herr := NewHTTPError(status, message...)
c.HandleError(herr)
}
func (c *Context) HandleError(err error) {
c.makross.HandleError(c, err)
}
func (c *Context) IsWebSocket() bool {
upgrade := c.Request.Header.Get(HeaderUpgrade)
return upgrade == "websocket" || upgrade == "Websocket"
}
// RealIP implements `Context#RealIP` function.
func (c *Context) RealIP() string {
ra := c.Request.RemoteAddr
if ip := c.Request.Header.Get(HeaderXForwardedFor); len(ip) > 0 {
ra = ip
} else if ip := c.Request.Header.Get(HeaderXRealIP); len(ip) > 0 {
ra = ip
} else {
ra, _, _ = net.SplitHostPort(ra)
}
return ra
}
// Param returns the named parameter value that is found in the URL path matching the current route.
// If the named parameter cannot be found, an empty string will be returned.
/*
func (c *Context) Param(name string) string {
for i, n := range c.pnames {
if n == name {
return c.pvalues[i]
}
}
return ""
}
*/
// Get returns the named data item previously registered with the context by calling Set.
// If the named data item cannot be found, nil will be returned.
func (c *Context) Get(name string) interface{} {
return c.data[name]
}
// Set stores the named data item in the context so that it can be retrieved later.
func (c *Context) Set(name string, value interface{}) {
if c.data == nil {
c.data = make(map[string]interface{})
}
c.data[name] = value
}
func (c *Context) SetStore(data map[string]interface{}) {
if c.data == nil {
c.data = make(map[string]interface{})
}
for k, v := range data {
c.data[k] = v
}
}
func (c *Context) GetStore() map[string]interface{} {
return c.data
}
func (c *Context) Pull(key string) interface{} {
return c.makross.data[key]
}
func (c *Context) Push(key string, value interface{}) {
if c.makross.data == nil {
c.makross.data = make(map[string]interface{})
}
c.makross.data[key] = value
}
func (c *Context) PullStore() map[string]interface{} {
return c.makross.data
}
func (c *Context) PushStore(data map[string]interface{}) {
if c.makross.data == nil {
c.makross.data = make(map[string]interface{})
}
for k, v := range data {
c.makross.data[k] = v
}
}
func (c *Context) Bind(i interface{}) error {
return c.makross.binder.Bind(i, c)
}
func (c *Context) UserAgent() string {
return c.Request.UserAgent()
}
func (c *Context) RequestURI() string {
return c.Request.RequestURI
}
func (c *Context) RequestBody() io.Reader {
rb, _ := c.Request.GetBody()
return rb
}
func (c *Context) MultipartForm() (*multipart.Form, error) {
err := c.Request.ParseMultipartForm(defaultMemory)
return c.Request.MultipartForm, err
}
func (c *Context) QueryString() string {
return c.Request.URL.RawQuery
}
func (c *Context) QueryParam(name string) string {
return c.Request.URL.Query().Get(name)
}
func (c *Context) QueryParams() url.Values {
return c.Request.URL.Query()
}
func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
_, fh, err := c.Request.FormFile(name)
return fh, err
}
func (c *Context) FormValue(name string) string {
return c.Request.FormValue(name)
}
func (c *Context) FormParams() (url.Values, error) {
if strings.HasPrefix(c.Request.Header.Get(HeaderContentType), MIMEMultipartForm) {
if err := c.Request.ParseMultipartForm(defaultMemory); err != nil {
return nil, err
}
} else {
if err := c.Request.ParseForm(); err != nil {
return nil, err
}
}
return c.Request.Form, nil
}
// Query returns the first value for the named component of the URL query parameters.
// If key is not present, it returns the specified default value or an empty string.
func (c *Context) Query(name string, defaultValue ...string) string {
if vs, _ := c.Request.URL.Query()[name]; len(vs) > 0 {
return vs[0]
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// Form returns the first value for the named component of the query.
// Form reads the value from POST and PUT body parameters as well as URL query parameters.
// The form takes precedence over the latter.
// If key is not present, it returns the specified default value or an empty string.
func (c *Context) Form(key string, defaultValue ...string) string {
r := c.Request
r.ParseMultipartForm(32 << 20)
if vs := r.Form[key]; len(vs) > 0 {
return vs[0]
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// PostForm returns the first value for the named component from POST and PUT body parameters.
// If key is not present, it returns the specified default value or an empty string.
func (c *Context) PostForm(key string, defaultValue ...string) string {
r := c.Request
r.ParseMultipartForm(32 << 20)
if vs := r.PostForm[key]; len(vs) > 0 {
return vs[0]
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// Next calls the rest of the handlers associated with the current route.
// If any of these handlers returns an error, Next will return the error and skip the following handlers.
// Next is normally used when a handler needs to do some postprocessing after the rest of the handlers
// are executed.
func (c *Context) Next() error {
c.index++
for n := len(c.handlers); c.index < n; c.index++ {
if err := c.handlers[c.index](c); err != nil {
return err
}
}
return nil
}
// Abort skips the rest of the handlers associated with the current route.
// Abort is normally used when a handler handles the request normally and wants to skip the rest of the handlers.
// If a handler wants to indicate an error condition, it should simply return the error without calling Abort.
func (c *Context) Abort() error {
c.index = len(c.handlers)
return nil
}
// Break 中断继续执行后续动作,返回指定状态及错误,不设置错误亦可.
func (c *Context) Break(status int, err ...error) error {
var e error
if len(err) > 0 {
e = err[0]
}
c.Response.WriteHeader(status)
c.HandleError(e)
return c.Abort()
}
// URL creates a URL using the named route and the parameter values.
// The parameters should be given in the sequence of name1, value1, name2, value2, and so on.
// If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL.
// Parameter values will be properly URL encoded.
// The method returns an empty string if the URL creation fails.
func (c *Context) URL(route string, pairs ...interface{}) string {
if r := c.makross.namedRoutes[route]; r != nil {
return r.URL(pairs...)
}
return ""
}
// Read populates the given struct variable with the data from the current request.
// If the request is NOT a GET request, it will check the "Content-Type" header
// and find a matching reader from DataReaders to read the request data.
// If there is no match or if the request is a GET request, it will use DefaultFormDataReader
// to read the request data.
func (c *Context) Read(data interface{}) error {
if c.Request.Method != "GET" {
t := getContentType(c.Request)
if reader, ok := DataReaders[t]; ok {
return reader.Read(c.Request, data)
}
}
return DefaultFormDataReader.Read(c.Request, data)
}
// Write writes the given data of arbitrary type to the response.
// The method calls the data writer set via SetDataWriter() to do the actual writing.
// By default, the DefaultDataWriter will be used.
func (c *Context) Write(data interface{}) error {
return c.writer.Write(c.Response, data)
}
func (c *Context) Redirect(url string, status ...int) error {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusFound
}
if code < StatusMultipleChoices || code > StatusPermanentRedirect {
return ErrInvalidRedirectCode
}
c.Response.Header().Set(HeaderLocation, url)
c.Response.WriteHeader(code)
return nil
}
func (c *Context) Render(name string, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
if c.makross.renderer == nil {
return ErrRendererNotRegistered
}
buf := new(bytes.Buffer)
if err = c.makross.renderer.Render(buf, name, c); err != nil {
return
}
c.Response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
c.Response.WriteHeader(code)
err = c.Write(buf.Bytes())
c.Abort()
return
}
func (c *Context) String(s string, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
c.Response.WriteHeader(code)
err = c.Write([]byte(s))
c.Abort()
return
}
func (c *Context) JSON(i interface{}, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
b, err := json.Marshal(i)
if err != nil {
return err
}
return c.JSONBlob(b, code)
}
func (c *Context) JSONPretty(i interface{}, indent string, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
b, err := json.MarshalIndent(i, "", indent)
if err != nil {
return
}
return c.JSONBlob(b, code)
}
func (c *Context) JSONBlob(b []byte, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
return c.Blob(MIMEApplicationJSONCharsetUTF8, b, code)
}
func (c *Context) JSONP(callback string, i interface{}, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
b, err := json.Marshal(i)
if err != nil {
return err
}
return c.JSONPBlob(callback, b, code)
}
func (c *Context) JSONPBlob(callback string, b []byte, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.Header().Set(HeaderContentType, MIMEApplicationJavaScriptCharsetUTF8)
c.Response.WriteHeader(code)
if err = c.Write([]byte(callback + "(")); err != nil {
return
}
if err = c.Write(b); err != nil {
return
}
err = c.Write([]byte(");"))
c.Abort()
return
}
func (c *Context) XML(i interface{}, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
b, err := xml.Marshal(i)
if err != nil {
return err
}
return c.XMLBlob(b, code)
}
func (c *Context) XMLPretty(i interface{}, indent string, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
b, err := xml.MarshalIndent(i, "", indent)
if err != nil {
return
}
return c.XMLBlob(b, code)
}
func (c *Context) XMLBlob(b []byte, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.Header().Set(HeaderContentType, MIMEApplicationXMLCharsetUTF8)
c.Response.WriteHeader(code)
if err = c.Write([]byte(xml.Header)); err != nil {
return
}
err = c.Write(b)
c.Abort()
return
}
func (c *Context) Blob(contentType string, b []byte, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.Header().Set(HeaderContentType, contentType)
c.Response.WriteHeader(code)
err = c.Write(b)
c.Abort()
return
}
func (c *Context) Stream(contentType string, r io.Reader, status ...int) (err error) {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.Header().Set(HeaderContentType, contentType)
c.Response.WriteHeader(code)
_, err = io.Copy(c.Response, r)
c.Abort()
return
}
// ServeFile serves a view file, to send a file ( zip for example) to the client
// you should use the SendFile(serverfilename,clientfilename)
//
// You can define your own "Content-Type" header also, after this function call
// This function doesn't implement resuming (by range), use ctx.SendFile/fasthttp.ServeFileUncompressed(ctx.RequestCtx,path)/fasthttpServeFile(ctx.RequestCtx,path) instead
//
// Use it when you want to serve css/js/... files to the client, for bigger files and 'force-download' use the SendFile
func (c *Context) ServeFile(file string) (err error) {
file, err = url.QueryUnescape(file) // Issue #839
if err != nil {
return
}
f, err := os.Open(file)
if err != nil {
return ErrNotFound
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
file = path.Join(file, indexPage)
f, err = os.Open(file)
if err != nil {
return ErrNotFound
}
fi, _ = f.Stat()
}
http.ServeContent(c.Response, c.Request, fi.Name(), fi.ModTime(), f)
return c.Abort() //c.ServeContent(f, fi.Name(), fi.ModTime())
}
// SendFile sends file for force-download to the client
//
// Use this instead of ServeFile to 'force-download' bigger files to the client
func (c *Context) SendFile(filename string, destinationName string) error {
f, err := os.Open(filename)
if err != nil {
return ErrNotFound
}
defer f.Close()
c.Response.Header().Set(HeaderContentDisposition, "attachment;filename="+destinationName)
_, err = io.Copy(c.Response, f)
c.Abort()
return err
}
func (c *Context) Attachment(file, name string) (err error) {
return c.contentDisposition(file, name, "attachment")
}
func (c *Context) Inline(file, name string) (err error) {
return c.contentDisposition(file, name, "inline")
}
func (c *Context) contentDisposition(file, name, dispositionType string) (err error) {
c.Response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name))
c.ServeFile(file)
return
}
// NoContent Only header
func (c *Context) NoContent(status ...int) error {
var code int
if len(status) > 0 {
code = status[0]
} else {
code = StatusOK
}
c.Response.WriteHeader(code)
return c.Abort()
}
// SetDataWriter sets the data writer that will be used by Write().
func (c *Context) SetDataWriter(writer DataWriter) {
c.writer = writer
}
func getContentType(req *http.Request) string {
t := req.Header.Get("Content-Type")
for i, c := range t {
if c == ' ' || c == ';' {
return t[:i]
}
}
return t
}
// ContentTypeByExtension returns the MIME type associated with the file based on
// its extension. It returns `application/octet-stream` incase MIME type is not
// found.
func (c *Context) ContentTypeByExtension(name string) (t string) {
ext := filepath.Ext(name)
//these should be found by the windows(registry) and unix(apache) but on windows some machines have problems on this part.
if t = mime.TypeByExtension(ext); t == "" {
// no use of map here because we will have to lock/unlock it, by hand is better, no problem:
if ext == ".json" {
t = MIMEApplicationJSON
} else if ext == ".zip" {
t = "application/zip"
} else if ext == ".3gp" {
t = "video/3gpp"
} else if ext == ".7z" {
t = "application/x-7z-compressed"
} else if ext == ".ace" {
t = "application/x-ace-compressed"
} else if ext == ".aac" {
t = "audio/x-aac"
} else if ext == ".ico" { // for any case
t = "image/x-icon"
} else if ext == ".png" {
t = "image/png"
} else {
t = MIMEOctetStream
}
}
return
}
// TimeFormat is the time format to use when generating times in HTTP
// headers. It is like time.RFC1123 but hard-codes GMT as the time
// zone. The time being formatted must be in UTC for Format to
// generate the correct format.
//
// For parsing this time format, see ParseTime.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
// RequestHeader returns the request header's value
// accepts one parameter, the key of the header (string)
// returns string
func (c *Context) RequestHeader(key string) string {
return c.Request.Header.Get(key)
}
// ServeContent serves content, headers are autoset
// receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string)
//
// You can define your own "Content-Type" header also, after this function call
// Doesn't implements resuming (by range), use ctx.SendFile instead
func (c *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time) error {
if t, err := time.Parse(TimeFormat, c.RequestHeader(HeaderIfModifiedSince)); err == nil && modtime.Before(t.Add(1*time.Second)) {
c.Response.Header().Del(HeaderContentType)
c.Response.Header().Del(HeaderContentLength)
c.Response.WriteHeader(StatusNotModified)
return nil
}
c.Response.Header().Set(HeaderContentType, c.ContentTypeByExtension(filename))
c.Response.Header().Set(HeaderLastModified, modtime.UTC().Format(TimeFormat))
size := func() int64 {
size, err := content.Seek(0, io.SeekEnd)
if err != nil {
return 0
}
_, err = content.Seek(0, io.SeekStart)
if err != nil {
return 0
}
return size
}()
c.Response.Header().Set(HeaderContentLength, fmt.Sprintf("%v", size))
c.Response.WriteHeader(StatusOK)
_, err := io.Copy(c.Response, content)
c.Abort()
return err
}
// IsTLS implements `Context#TLS` function.
func (c *Context) IsTLS() bool {
return c.Request.TLS != nil
}
func (c *Context) Scheme() string {
// Can't use `r.Request.URL.Scheme`
// See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0
if c.IsTLS() {
return "https"
}
if scheme := c.Request.Header.Get(HeaderXForwardedProto); scheme != "" {
return scheme
}
if scheme := c.Request.Header.Get(HeaderXForwardedProtocol); scheme != "" {
return scheme
}
if ssl := c.Request.Header.Get(HeaderXForwardedSsl); ssl == "on" {
return "https"
}
if scheme := c.Request.Header.Get(HeaderXUrlScheme); scheme != "" {
return scheme
}
return "http"
}