-
Notifications
You must be signed in to change notification settings - Fork 2
/
context.go
574 lines (516 loc) · 15.6 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
package evo
//DO NOT EDIT THIS FILE
import (
"bytes"
"encoding/json"
"fmt"
"github.com/CloudyKit/jet/v6"
"github.com/getevo/evo-ng/lib/generic"
"github.com/getevo/evo-ng/lib/shared"
"github.com/getevo/evo/lib/log"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"io"
"mime/multipart"
"net/url"
"reflect"
"strings"
"time"
)
// Cookie container wrapper struct
type Cookie fiber.Cookie
// Response represent formal form of response defined by evo
type Response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Error []error `json:"error,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// URL describe url
type URL struct {
Query url.Values
Host string
Scheme string
Path string
Raw string
}
// Cookie is used for getting a cookie value by key.
// value accepts string,int,int64,int8,int32,int16,uint,uint64,uint8,uint16,uint32,float32,float64,complex64,complex128 as value of cookie
// value accepts struct and turn it into json string as value of cookie
// value accepts time.Time,time.Duration as expiration time of cookie
// value accepts fiber.Cookie,request.Cookie as custom cookie settings
// Make copies or use the Immutable setting to use the value outside the Handler.
func (ctx *Context) Cookie(key string, value ...interface{}) generic.Value {
if len(value) > 0 {
var cookie = fiber.Cookie{}
for _, item := range value {
switch val := item.(type) {
case Cookie:
cookie = fiber.Cookie(val)
case *Cookie:
cookie = fiber.Cookie(*val)
case fiber.Cookie:
cookie = val
case *fiber.Cookie:
cookie = *val
case time.Duration:
cookie.Expires = time.Now().Add(val)
case time.Time:
cookie.Expires = val
case string:
cookie.Value = val
case int, int64, int8, int32, int16, uint, uint64, uint8, uint16, uint32, float32, float64, complex64, complex128:
cookie.Value = fmt.Sprint(val)
default:
var b, err = json.Marshal(val)
if err != nil {
log.Error(err)
} else {
cookie.Value = string(b)
}
}
}
cookie.Name = key
ctx.fiber.Cookie(&cookie)
}
return generic.Parse(ctx.fiber.Cookies(key))
}
// Header set/get the HTTP request header specified by field and value.
// Field names are case-insensitive
// value will be join by semicolon in case of more than one
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *Context) Header(key string, value ...string) string {
if len(value) > 0 {
c.FastHTTP().Response.Header.Set(key, strings.Join(value, ";"))
}
return c.fiber.Get(key)
}
// Status sets the HTTP status for the response.
// This method is chainable.
// @receiver c
// @param status
// @return *Context
func (c *Context) Status(status int) *Context {
c.FastHTTP().Response.SetStatusCode(status)
return c
}
// Query returns the query string parameter in the url.
// Defaults to empty string "" if the query doesn't exist.
// If a default value is given, it will return that value if the query doesn't exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
// @receiver ctx
// @param key
// @param defaultValue
// @return string
func (ctx *Context) Query(key string, defaultValue ...string) string {
return ctx.fiber.Query(key, defaultValue...)
}
// Protocol contains the request protocol string: http or https for TLS requests.
// @receiver ctx
// @return string
func (ctx *Context) Protocol() string {
return ctx.fiber.Protocol()
}
// Hostname contains the hostname derived from the Host HTTP header.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
// @receiver c
// @return string
func (c *Context) Hostname() string {
return c.fiber.Hostname()
}
// IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.
// @receiver c
// @return ips
func (c *Context) IPs() (ips []string) {
return c.fiber.IPs()
}
// Is returns the matching content type,
// if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
// @receiver c
// @param extension
// @return bool
func (c *Context) Is(extension string) bool {
return c.fiber.Is(extension)
}
// Locals makes it possible to pass interface{} values under string keys scoped to the request
// and therefore available to all following routes that match the request.
// @receiver c
// @param key
// @param value
// @return generic.Value
func (c *Context) Locals(key string, value ...interface{}) generic.Value {
return generic.Parse(c.fiber.Locals(key, value...))
}
// Location sets the response Location HTTP header to the specified path parameter.
// @receiver c
// @param path
func (c *Context) Location(path string) {
c.fiber.Location(path)
}
// Redirect to the URL derived from the specified path, with specified status.
// If status is not specified, status defaults to 302 Found.
// @receiver c
// @param location
// @param status
func (c *Context) Redirect(location string, status ...int) {
c.fiber.Redirect(location, status...)
}
// Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
// @receiver c
// @param override
// @return string
func (c *Context) Method(override ...string) string {
return c.fiber.Method()
}
// Subdomains returns a string slice of subdomains in the domain name of the request.
// The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
// @receiver c
// @param offset
// @return []string
func (c *Context) Subdomains(offset ...int) []string {
o := 2
if len(offset) > 0 {
o = offset[0]
}
subdomains := strings.Split(c.Hostname(), ".")
l := len(subdomains) - o
// Check index to avoid slice bounds out of range panic
if l < 0 {
l = len(subdomains)
}
subdomains = subdomains[:l]
return subdomains
}
// String returns unique string representation of the ctx.
//
// The returned value may be useful for logging.
func (c *Context) String() string {
return c.fiber.String()
}
// Vary adds the given header field to the Vary response header.
// This will append the header, if not already listed, otherwise leaves it listed in the current location.
func (c *Context) Vary(fields ...string) {
c.fiber.Vary(fields...)
}
// Accepts checks if the specified extensions or content types are acceptable.
func (c *Context) Accepts(offers ...string) string {
return c.fiber.Accepts(offers...)
}
// AcceptsCharsets checks if the specified charset is acceptable.
func (c *Context) AcceptsCharsets(offers ...string) string {
return c.fiber.AcceptsCharsets(offers...)
}
// AcceptsEncodings checks if the specified encoding is acceptable.
func (c *Context) AcceptsEncodings(offers ...string) string {
return c.fiber.AcceptsEncodings(offers...)
}
// AcceptsLanguages checks if the specified language is acceptable.
func (c *Context) AcceptsLanguages(offers ...string) string {
return c.fiber.AcceptsLanguages(offers...)
}
// ClearCookie expires a specific cookie by key on the client side.
// If no key is provided it expires all cookies that came with the request.
func (c *Context) ClearCookie(key ...string) {
c.fiber.ClearCookie(key...)
}
// 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 *Context) Download(file string, filename ...string) error {
return c.fiber.Download(file, filename...)
}
// Fresh check if this request is fresh and is not beign cached
// @receiver c
// @return bool
func (c *Context) Fresh() bool {
return c.fiber.Fresh()
}
// Request return the *fasthttp.Request object
// This allows you to use all fasthttp request methods
// https://godoc.org/github.com/valyala/fasthttp#Request
// @receiver c
// @return *fasthttp.Request
func (c *Context) Request() *fasthttp.Request {
return c.fiber.Request()
}
// Response return the *fasthttp.Response object
// @receiver c
// @return *fasthttp.Response
// This allows you to use all fasthttp response methods
// https://godoc.org/github.com/valyala/fasthttp#Response
func (c *Context) Response() *fasthttp.Response {
return c.fiber.Response()
}
// Format performs content-negotiation on the Accept HTTP header.
// @receiver c
// @param body
// @return error
// It uses Accepts to select a proper format.
// If the header is not specified or there is no proper format, text/plain is used.
func (c *Context) Format(body interface{}) error {
return c.fiber.Format(body)
}
// FormFile returns the first file by key from a MultipartForm.
// @receiver c
// @param key
// @return *multipart.FileHeader
// @return error
func (c *Context) FormFile(key string) (*multipart.FileHeader, error) {
return c.fiber.FormFile(key)
}
// MultipartForm parse form entries from binary.
// This returns a map[string][]string, so given a key the value will be a string slice.
// @receiver c
// @return *multipart.Form
// @return error
func (c *Context) MultipartForm() (*multipart.Form, error) {
return c.FastHTTP().MultipartForm()
}
// FastHTTP returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
// @receiver c
// @return *fasthttp.RequestCtx
func (c *Context) FastHTTP() *fasthttp.RequestCtx {
return c.fiber.Context()
}
// XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
// indicating that the request was issued by a client library (such as jQuery).
// @receiver c
// @return bool
func (c *Context) XHR() bool {
return c.fiber.XHR()
}
// Route returns the matched Route struct.
// @receiver c
// @return *fiber.Route
func (c *Context) Route() *fiber.Route {
return c.fiber.Route()
}
// SaveFile saves any multipart file to disk.
// @receiver c
// @param fileheader
// @param path
// @return error
func (c *Context) SaveFile(fileheader *multipart.FileHeader, path string) error {
return fasthttp.SaveMultipartFile(fileheader, path)
}
// Secure returns a boolean property, that is true, if a TLS connection is established.
// @receiver c
// @return bool
func (c *Context) Secure() bool {
return c.FastHTTP().IsTLS()
}
// WriteBytes sets the HTTP response body without copying it.
// From this point onward the body argument must not be changed.
// @receiver c
// @param body
func (c *Context) WriteBytes(body []byte) {
// Write response body
c.FastHTTP().Response.SetBodyRaw(body)
}
// WriteString sets the HTTP response body without copying it.
// From this point onward the body argument must not be changed.
// @receiver c
// @param body
func (c *Context) WriteString(body string) {
// Write response body
c.fiber.Send([]byte(body))
}
// SendFile transfers the file from the given path.
// The file is not compressed by default, enable this by passing a 'true' argument
// Sets the Content-Type response HTTP header field based on the filenames extension.
// @receiver c
// @param file
// @param compress
// @return error
func (c *Context) SendFile(file string, compress ...bool) error {
return c.fiber.SendFile(file, compress...)
}
// SendStatus sets the HTTP status code and if the response body is empty,
// it sets the correct status message in the body.
// @receiver c
// @param status
// @return error
func (c *Context) SendStatus(status int) error {
return c.fiber.SendStatus(status)
}
// SendStream sets response body stream and optional body size.
// @receiver c
// @param stream
// @param size
// @return error
func (c *Context) SendStream(stream io.Reader, size ...int) error {
return c.fiber.SendStream(stream, size...)
}
// WriteJSON sets the HTTP response body without copying it.
// From this point onward the body argument must not be changed.
// @receiver c
// @param body
func (c *Context) WriteJSON(body interface{}) {
// Write response body
var b, err = json.Marshal(body)
if err != nil {
c.fiber.Status(400)
c.fiber.WriteString(err.Error())
} else {
c.fiber.Write(b)
}
}
// WriteResponse writes json Response object to http response
// @receiver c
// @param args
func (c *Context) WriteResponse(args ...interface{}) {
var resp = Response{}
var s = false
for _, arg := range args {
switch val := arg.(type) {
case string:
resp.Message = val
case error:
resp.Error = append(resp.Error, val)
case bool:
s = true
resp.Success = val
default:
resp.Data = val
}
}
if !s && (resp.Data != nil || resp.Message != "") {
resp.Success = true
}
c.WriteJSON(resp)
}
// Write generic write function
// @receiver c
// @param data
func (c *Context) Write(data interface{}) {
switch w := data.(type) {
case []byte:
c.fiber.Write(w)
case string:
c.fiber.Write([]byte(w))
case int, int64, int8, int32, int16, uint, uint64, uint8, uint16, uint32, float32, float64, complex64, complex128:
c.fiber.WriteString(fmt.Sprint(w))
case error:
c.fiber.Status(400)
c.fiber.WriteString(w.Error())
default:
var b, err = json.Marshal(w)
if err != nil {
c.fiber.Status(400)
c.fiber.WriteString(err.Error())
} else {
c.fiber.Write(b)
}
}
}
// Next executes the message method in the stack that matches the current route.
// @receiver c
// @return error
func (c *Context) Next() error {
return c.fiber.Next()
}
// Fiber returns underlying fiber context
// @receiver c
// @return *fiber.Ctx
func (c *Context) Fiber() *fiber.Ctx {
return c.fiber
}
// Router keep prefix of the path group
type Router struct {
Prefix string
}
// Group create group of routers
// @param url
// @return Router
func Group(url string) Router {
return Router{
Prefix: url,
}
}
// Group create group of routers
// @receiver r
// @param url
// @return Router
func (r Router) Group(url string) Router {
return Router{
Prefix: r.Prefix + url,
}
}
// View render a view into output
// @receiver c
// @param env
// @param view
// @param data
// @return error
func (c *Context) View(env, view string, data ...interface{}) error {
var vars = jet.VarMap{}
if e, ok := shared.Views[env]; ok {
var v, err = e.GetTemplate(view)
if err != nil {
return err
}
for i, item := range data {
switch c := item.(type) {
case string:
if len(data) > i+1 {
vars[c] = reflect.ValueOf(data[i+1])
}
case map[string]interface{}:
for key, val := range c {
vars[key] = reflect.ValueOf(val)
}
}
}
vars["request"] = reflect.ValueOf(c)
var buff = bytes.Buffer{}
err = v.Execute(&buff, vars, nil)
if err != nil {
return err
}
c.Header("Content-Type", "text/html")
c.Status(200)
c.WriteBytes(buff.Bytes())
return nil
}
return fmt.Errorf("invalid environment %s", env)
}
// URL parse parts of the url
// @receiver c
// @return *URL
func (c *Context) URL() *URL {
u := URL{}
var fiber = c.Fiber()
base := strings.Split(fiber.BaseURL(), "://")
u.Scheme = base[0]
u.Host = c.Hostname()
u.Raw = fiber.OriginalURL()
parts := strings.Split(u.Raw, "?")
if len(parts) == 1 {
u.Query = url.Values{}
u.Path = u.Raw
} else {
u.Path = parts[0]
u.Query, _ = url.ParseQuery(strings.Join(parts[1:], "?"))
}
return &u
}
// Set set url query string variable
// @receiver u
// @param key
// @param value
// @return *URL
func (u *URL) Set(key string, value interface{}) *URL {
u.Query.Set(key, fmt.Sprint(value))
return u
}
// String build string url of URL struct
// @receiver u
// @return string
func (u *URL) String() string {
return u.Path + "?" + u.Query.Encode()
}