Repository navigation
Expand file tree
/
Copy pathcontext.go
More file actions
1827 lines (1605 loc) · 43.2 KB
/
Copy pathcontext.go
File metadata and controls
1827 lines (1605 loc) · 43.2 KB
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package flow
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-think/flow/session"
)
// --- Begin request.go ---
// Request HTTP request
type Request struct {
Request *http.Request
ctx context.Context
method string
path string
query map[string]string
queryValues url.Values
post map[string]string
postValues url.Values
routeParams map[string]string
routeParamsMu sync.RWMutex
originalParams map[string]string
routeParamObjects map[string]any
routeMiddlewares []interface{}
currentRoute *Route
files map[string]*File
bodyContent []byte
session session.Session
CookieHandler *Cookie
writer http.ResponseWriter
keys map[string]interface{}
keysMu sync.RWMutex
parseOnce sync.Once
canonical *Response
}
// CanonicalResponse returns the lazily-created response bound to this
// request. The Context type and response-preparation share this instance so
// header mutations from middlewares reach the final output.
func (r *Request) CanonicalResponse() *Response {
if r.canonical == nil {
r.canonical = NewResponse()
}
return r.canonical
}
// Context is the request-scoped handle given to route actions: it wraps the
// request, its route parameters and the canonical response.
type Context struct {
*Request
response *Response
}
// contextType is the reflect type used for Context argument injection.
var contextType = reflect.TypeOf(Context{})
// newContext builds a Context bound to the request's canonical response.
func newContext(request *Request) Context {
return Context{Request: request, response: request.CanonicalResponse()}
}
// Param returns a route parameter value for the current request.
func (c Context) Param(name string) string {
return c.Request.GetRouteParam(name)
}
// Response returns the canonical response for the current request; header
// mutations made through it reach the final output.
func (c Context) Response() *Response {
return c.response
}
// String writes a plain-text response body with the given status code.
func (c Context) String(code int, body string) Response {
res := c.response
res.SetCode(code).SetContent(body)
return *res
}
// Header sets a single response header.
func (r *Response) Header(name, value string) *Response {
if r.headers == nil {
r.headers = make(http.Header)
}
r.headers.Set(name, value)
return r
}
// Headers returns the full response header map.
func (r *Response) Headers() http.Header {
if r.headers == nil {
r.headers = make(http.Header)
}
return r.headers
}
// StatusCode returns the HTTP status code of the response.
func (r *Response) StatusCode() int {
return r.code
}
// Body returns the response content.
func (r *Response) Body() string {
return r.content
}
// ResponseWriter returns the native http.ResponseWriter associated with this request.
func (r *Request) ResponseWriter() http.ResponseWriter {
return r.writer
}
// SetResponseWriter sets the native http.ResponseWriter for direct writing.
func (r *Request) SetResponseWriter(w http.ResponseWriter) *Request {
r.writer = w
return r
}
// NewRequest create a new HTTP request from *http.Request
func NewRequest(req *http.Request) *Request {
ctx := context.Background()
method := ""
path := ""
if req != nil {
if req.Context() != nil {
ctx = req.Context()
}
method = req.Method
if req.URL != nil {
path = req.URL.Path
}
}
return &Request{
Request: req,
ctx: ctx,
method: method,
path: path,
routeParams: make(map[string]string),
files: make(map[string]*File),
keys: make(map[string]interface{}),
}
}
// Context returns the request's context.Context
func (r *Request) Context() context.Context {
if r.ctx == nil {
return context.Background()
}
return r.ctx
}
// WithContext sets the request's context.Context
func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
return r
}
r.ctx = ctx
if r.Request != nil {
r.Request = r.Request.WithContext(ctx)
}
return r
}
// Set store a new key/value pair in this context
func (r *Request) Set(key string, value interface{}) {
r.keysMu.Lock()
defer r.keysMu.Unlock()
if r.keys == nil {
r.keys = make(map[string]interface{})
}
r.keys[key] = value
}
// Get returns the value for the given key
func (r *Request) Get(key string) (value interface{}, exists bool) {
r.keysMu.RLock()
defer r.keysMu.RUnlock()
value, exists = r.keys[key]
return
}
// GetMethod get the request method.
func (r *Request) GetMethod() string {
return r.method
}
// GetPath get the request path.
// SetPath overrides the request path (used internally for route dispatch).
func (r *Request) SetPath(path string) {
r.path = "/" + strings.TrimLeft(path, "/")
}
func (r *Request) GetPath() string {
return r.path
}
// GetHttpRequest get Current *http.Request
func (r *Request) GetHttpRequest() *http.Request {
return r.Request
}
// IsMethod checks if the request method is of specified type.
func (r *Request) IsMethod(m string) bool {
return strings.ToUpper(m) == r.GetMethod()
}
// SetRoute stores the matched route on the request
// ).
func (r *Request) SetRoute(route *Route) { r.currentRoute = route }
// Route returns the route matched for this request, if any.
func (r *Request) Route() *Route { return r.currentRoute }
// SetRouteParam sets a route parameter by name
func (r *Request) SetRouteParam(name, value string) {
r.routeParamsMu.Lock()
defer r.routeParamsMu.Unlock()
r.routeParams[name] = value
}
// ForgetRouteParam removes a route parameter by name
// .
func (r *Request) ForgetRouteParam(name string) {
r.routeParamsMu.Lock()
defer r.routeParamsMu.Unlock()
delete(r.routeParams, name)
}
// routeParamsSnapshot returns a copy of the current route parameters.
func (r *Request) routeParamsSnapshot() map[string]string {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
out := make(map[string]string, len(r.routeParams))
for k, v := range r.routeParams {
out[k] = v
}
return out
}
// RouteParams returns a copy of the current route parameters.
func (r *Request) RouteParams() map[string]string {
return r.routeParamsSnapshot()
}
// SetOriginalParams records the bind-time snapshot of the route parameters
// .
func (r *Request) SetOriginalParams(params []*parameter) {
r.routeParamsMu.Lock()
defer r.routeParamsMu.Unlock()
if r.originalParams == nil {
r.originalParams = make(map[string]string, len(params))
}
for _, p := range params {
r.originalParams[p.name] = p.value
}
}
// OriginalParams returns the bind-time snapshot of the route parameters.
func (r *Request) OriginalParams() map[string]string {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
out := make(map[string]string, len(r.originalParams))
for k, v := range r.originalParams {
out[k] = v
}
return out
}
// GetOriginalRouteParam returns a parameter from the bind-time snapshot.
func (r *Request) GetOriginalRouteParam(key string, defaultValue ...string) string {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
if v, ok := r.originalParams[key]; ok {
return v
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// SetRouteParamObject stores an object resolved for a route parameter
// .
func (r *Request) SetRouteParamObject(name string, value any) {
r.routeParamsMu.Lock()
defer r.routeParamsMu.Unlock()
if r.routeParamObjects == nil {
r.routeParamObjects = make(map[string]any)
}
r.routeParamObjects[name] = value
}
// RouteParamObject returns the object resolved for a route parameter, if any.
func (r *Request) RouteParamObject(name string) (any, bool) {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
v, ok := r.routeParamObjects[name]
return v, ok
}
// RouteMiddlewares Returns the route middlewares matched for the request.
func (r *Request) RouteMiddlewares() []interface{} {
return r.routeMiddlewares
}
// SetRouteMiddlewares Sets the route middlewares matched for the request.
func (r *Request) SetRouteMiddlewares(middlewares []interface{}) {
r.routeMiddlewares = append(r.routeMiddlewares, middlewares...)
}
// GetRouteParam gets a route parameter
func (r *Request) GetRouteParam(key string, defaultValue ...string) string {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
if v, ok := r.routeParams[key]; ok {
return v
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// RouteParam returns a route parameter with error if not present
func (r *Request) RouteParam(key string, defaultValue ...string) (string, error) {
r.routeParamsMu.RLock()
defer r.routeParamsMu.RUnlock()
if v, ok := r.routeParams[key]; ok {
return v, nil
}
if len(defaultValue) > 0 {
return defaultValue[0], nil
}
return "", errors.New("route parameter not present")
}
func (r *Request) parseInputOnce() {
r.parseOnce.Do(func() {
if r.Request != nil && r.Request.URL != nil {
r.queryValues = r.Request.URL.Query()
r.query = parseQuery(r.queryValues)
}
if r.Request != nil {
r.postValues, r.post = parsePost(r.Request)
// Parse JSON body if applicable
if r.IsJson() {
body, _ := r.GetContent()
if len(body) > 0 {
var jsonData map[string]interface{}
if err := json.Unmarshal(body, &jsonData); err == nil {
for k, v := range jsonData {
r.post[k] = fmt.Sprintf("%v", v)
}
}
}
}
}
})
}
// Query returns a query string item from the request.
func (r *Request) Query(key string, value ...string) (string, error) {
r.parseInputOnce()
if v, ok := r.query[key]; ok {
return v, nil
}
if len(value) > 0 {
return value[0], nil
}
return "", errors.New("named query not present")
}
// Input returns a input item from the request.
func (r *Request) Input(key string, value ...string) (string, error) {
r.parseInputOnce()
if v, ok := r.post[key]; ok {
return v, nil
}
if v, ok := r.query[key]; ok {
return v, nil
}
if len(value) > 0 {
return value[0], nil
}
return "", errors.New("named input not present")
}
// Post returns a post item from the request.
func (r *Request) Post(key string, value ...string) (string, error) {
r.parseInputOnce()
if v, ok := r.post[key]; ok {
return v, nil
}
if len(value) > 0 {
return value[0], nil
}
return "", errors.New("named post not present")
}
// Cookie Retrieve a cookie from the request.
func (r *Request) Cookie(key string, value ...string) (string, error) {
var err error
if r.Request == nil {
if len(value) > 0 {
return value[0], nil
}
return "", errors.New("nil http request")
}
if r.CookieHandler == nil {
r.CookieHandler = ParseCookieHandler()
}
prefix := ""
if r.CookieHandler != nil && r.CookieHandler.Config != nil {
prefix = r.CookieHandler.Config.Prefix
}
key = prefix + key
cookie, err := r.Request.Cookie(key)
if err == nil {
c, _ := url.QueryUnescape(cookie.Value)
return c, err
}
if len(value) > 0 {
return value[0], nil
}
return "", err
}
// SetCookieHandler sets the Cookie handler for the request.
func (r *Request) SetCookieHandler(handler *Cookie) {
r.CookieHandler = handler
}
// File returns a file from the request.
func (r *Request) File(key string) (*File, error) {
if f, ok := r.files[key]; ok {
return f, nil
}
if r.Request == nil {
return nil, errors.New("nil http request")
}
_, fh, err := r.Request.FormFile(key)
if err != nil {
return nil, err
}
r.files[key] = &File{fh}
return r.files[key], nil
}
// HasFile determines if the uploaded data contains a file.
func (r *Request) HasFile(key string) bool {
if _, ok := r.files[key]; ok {
return true
}
if r.Request == nil {
return false
}
_, _, err := r.Request.FormFile(key)
return err == nil
}
// AllFiles returns all files from the request.
func (r *Request) AllFiles() (map[string]*File, error) {
if r.Request == nil {
return nil, errors.New("nil http request")
}
err := r.Request.ParseMultipartForm(32 << 20)
if err != nil && err != http.ErrNotMultipart {
return nil, err
}
if r.Request.MultipartForm != nil && r.Request.MultipartForm.File != nil {
for key, fh := range r.Request.MultipartForm.File {
if len(fh) > 0 {
r.files[key] = &File{fh[0]}
}
}
}
return r.files, nil
}
// Files returns all uploaded files for the given form key (supports multi-file uploads e.g. "photos" or "photos[]").
func (r *Request) Files(key string) []*File {
if r.Request == nil {
return nil
}
if r.Request.MultipartForm == nil {
_ = r.Request.ParseMultipartForm(32 << 20)
}
if r.Request.MultipartForm == nil || r.Request.MultipartForm.File == nil {
return nil
}
headers := r.Request.MultipartForm.File[key]
if len(headers) == 0 {
headers = r.Request.MultipartForm.File[key+"[]"]
}
if len(headers) == 0 {
return nil
}
files := make([]*File, len(headers))
for i, fh := range headers {
files[i] = &File{FileHeader: fh}
}
return files
}
// All get all of the input and query for the request.
func (r *Request) All(keys ...string) map[string]string {
r.parseInputOnce()
all := mergeForm(r.query, r.post)
if len(keys) == 0 {
return all
}
result := make(map[string]string)
for _, key := range keys {
if v, ok := all[key]; ok {
result[key] = v
} else {
result[key] = ""
}
}
return result
}
// Only get a subset of the items from the input data.
func (r *Request) Only(keys ...string) map[string]string {
all := r.All()
result := make(map[string]string)
for _, key := range keys {
if v, ok := all[key]; ok {
result[key] = v
}
}
return result
}
// Except Get all of the input except for a specified array of items.
func (r *Request) Except(keys ...string) map[string]string {
all := r.All()
for _, key := range keys {
delete(all, key)
}
return all
}
// Has Determine if the request contains a given input item key (including empty strings).
func (r *Request) Has(keys ...string) bool {
if len(keys) == 0 {
return false
}
all := r.All()
for _, key := range keys {
if _, ok := all[key]; !ok {
return false
}
}
return true
}
// HasAny Determine if the request contains any of the given keys.
func (r *Request) HasAny(keys ...string) bool {
if len(keys) == 0 {
return false
}
all := r.All()
for _, key := range keys {
if _, ok := all[key]; ok {
return true
}
}
return false
}
// Filled Determine if the request contains a non-empty value for an input item.
func (r *Request) Filled(keys ...string) bool {
if len(keys) == 0 {
return false
}
all := r.All()
for _, key := range keys {
v, ok := all[key]
if !ok || strings.TrimSpace(v) == "" {
return false
}
}
return true
}
// Missing Determine if the given input key is completely missing from the request.
func (r *Request) Missing(keys ...string) bool {
if len(keys) == 0 {
return true
}
all := r.All()
for _, key := range keys {
if _, ok := all[key]; ok {
return false
}
}
return true
}
// Exists Determine if the request contains a given input item key (alias of Has).
func (r *Request) Exists(keys ...string) bool {
return r.Has(keys...)
}
// Url get the URL (no query string) for the request.
func (r *Request) Url() string {
return r.Request.URL.Path
}
// FullUrl get the full URL for the request.
func (r *Request) FullUrl() string {
if r.Request != nil && r.Request.URL != nil && r.Request.URL.RawQuery != "" {
return r.Url() + "?" + r.Request.URL.RawQuery
}
return r.Url()
}
// Path get the current path info for the request.
func (r *Request) Path() string {
return r.path
}
// Method get the current method for the request.
func (r *Request) Method() string {
return r.method
}
// GetContent Returns the request body content.
func (r *Request) GetContent() ([]byte, error) {
if r.bodyContent != nil {
return r.bodyContent, nil
}
if r.Request == nil || r.Request.Body == nil {
return nil, nil
}
body, err := io.ReadAll(r.Request.Body)
if err != nil {
return nil, err
}
r.bodyContent = body
r.Request.Body = io.NopCloser(bytes.NewBuffer(body))
return body, nil
}
// Session get the session associated with the request.
func (r *Request) Session() session.Session {
return r.session
}
// Session set the session associated with the request.
func (r *Request) SetSession(s session.Session) {
r.session = s
}
func parseQuery(q url.Values) map[string]string {
query := make(map[string]string)
for k, v := range q {
if len(v) > 0 {
query[k] = v[0]
}
}
return query
}
func parsePost(r *http.Request) (url.Values, map[string]string) {
postMap := make(map[string]string)
if r == nil {
return nil, postMap
}
_ = r.ParseForm()
values := url.Values{}
for k, v := range r.PostForm {
values[k] = append(values[k], v...)
if len(v) > 0 {
postMap[k] = v[0]
}
}
_ = r.ParseMultipartForm(32 << 20)
if r.MultipartForm != nil {
for k, v := range r.MultipartForm.Value {
values[k] = append(values[k], v...)
if len(v) > 0 {
postMap[k] = v[0]
}
}
}
return values, postMap
}
func mergeForm(slices ...map[string]string) map[string]string {
r := make(map[string]string)
for _, slice := range slices {
for k, v := range slice {
r[k] = v
}
}
return r
}
// Header returns the value of the given header key.
func (r *Request) Header(key string) string {
if r.Request != nil {
return r.Request.Header.Get(key)
}
return ""
}
// BearerToken returns the Bearer token from the Authorization header.
func (r *Request) BearerToken() string {
auth := r.Header("Authorization")
if strings.HasPrefix(auth, "Bearer ") {
return auth[7:]
}
return ""
}
// ClientIP returns the client IP.
func (r *Request) ClientIP() string {
if r.Request == nil {
return ""
}
if ip := r.Header("X-Real-Ip"); ip != "" {
return ip
}
if ip := r.Header("X-Forwarded-For"); ip != "" {
return strings.Split(ip, ",")[0]
}
// RemoteAddr could be IP:port
addr := r.Request.RemoteAddr
if idx := strings.LastIndex(addr, ":"); idx != -1 {
return addr[:idx]
}
return addr
}
// WantsJson returns true if the request asks for a JSON response.
func (r *Request) WantsJson() bool {
accept := r.Header("Accept")
return strings.Contains(accept, "/json") || strings.Contains(accept, "+json")
}
// ExpectsJson returns true if the request expects a JSON response.
func (r *Request) ExpectsJson() bool {
return r.IsAjax() || r.WantsJson()
}
// IsAjax returns true if the request is an AJAX request.
func (r *Request) IsAjax() bool {
return r.Header("X-Requested-With") == "XMLHttpRequest"
}
// Boolean retrieves an input item as a boolean.
func (r *Request) Boolean(key string, defaultValue ...bool) bool {
val, err := r.Input(key)
if err != nil || val == "" {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return false
}
lower := strings.ToLower(strings.TrimSpace(val))
switch lower {
case "1", "true", "t", "yes", "y", "on":
return true
case "0", "false", "f", "no", "n", "off":
return false
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return false
}
// Integer retrieves an input item as an integer.
func (r *Request) Integer(key string, defaultValue ...int) int {
val, err := r.Input(key)
if err != nil || val == "" {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0
}
intVal, err := strconv.Atoi(strings.TrimSpace(val))
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0
}
return intVal
}
// Float retrieves an input item as a float64.
func (r *Request) Float(key string, defaultValue ...float64) float64 {
val, err := r.Input(key)
if err != nil || val == "" {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0.0
}
floatVal, err := strconv.ParseFloat(strings.TrimSpace(val), 64)
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0.0
}
return floatVal
}
// Merge merges new input into the current request's user input.
func (r *Request) Merge(values map[string]string) *Request {
r.parseInputOnce()
if r.post == nil {
r.post = make(map[string]string)
}
for k, v := range values {
r.post[k] = v
if r.query != nil {
if _, ok := r.query[k]; ok {
r.query[k] = v
}
}
}
return r
}
// Fingerprint gets a unique fingerprint for the request.
func (r *Request) Fingerprint() string {
ip := r.ClientIP()
ua := r.Header("User-Agent")
route := r.GetPath()
method := r.GetMethod()
hash := sha256.Sum256(fmt.Appendf(nil, "%s|%s|%s|%s", method, route, ip, ua))
return hex.EncodeToString(hash[:])
}
// UserAgent returns the client User-Agent header.
func (r *Request) UserAgent() string {
return r.Header("User-Agent")
}
// Segments gets all segments of the request path.
func (r *Request) Segments() []string {
trimmed := strings.Trim(r.Path(), "/")
if trimmed == "" {
return []string{}
}
return strings.Split(trimmed, "/")
}
// Segment gets a 1-indexed segment of the path.
func (r *Request) Segment(index int, defaultValue ...string) string {
segments := r.Segments()
if index > 0 && index <= len(segments) {
return segments[index-1]
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
}
// Is determines if the current request path matches given patterns.
func (r *Request) Is(patterns ...string) bool {
path := strings.Trim(r.Path(), "/")
for _, pattern := range patterns {
pattern = strings.Trim(pattern, "/")
if pattern == path {
return true
}
if strings.Contains(pattern, "*") {
pat := "^" + strings.ReplaceAll(regexp.QuoteMeta(pattern), "\\*", ".*") + "$"
if matched, _ := regexp.MatchString(pat, path); matched {
return true
}
}
}
return false
}
// RouteIs determines if the current route name matches given patterns.
func (r *Request) RouteIs(patterns ...string) bool {
routeName := ""
if nameVal, ok := r.Get("_route_name"); ok {
if nameStr, ok := nameVal.(string); ok {
routeName = nameStr
}
}
if routeName == "" {
return false
}
for _, pattern := range patterns {
if pattern == routeName {
return true
}
if strings.Contains(pattern, "*") {
pat := "^" + strings.ReplaceAll(regexp.QuoteMeta(pattern), "\\*", ".*") + "$"
if matched, _ := regexp.MatchString(pat, routeName); matched {
return true
}
}
}
return false
}
// FullUrlWithQuery appends or replaces query parameters to current full URL.
func (r *Request) FullUrlWithQuery(query map[string]string) string {
if r.Request == nil || r.Request.URL == nil {
return ""
}
q := r.Request.URL.Query()
for k, v := range query {
q.Set(k, v)
}
encoded := q.Encode()
if encoded == "" {
return r.Url()
}
return r.Url() + "?" + encoded
}
// FullUrlWithoutQuery removes specified query parameters from current full URL.
func (r *Request) FullUrlWithoutQuery(keys ...string) string {
if r.Request == nil || r.Request.URL == nil {
return ""
}
q := r.Request.URL.Query()
for _, k := range keys {
q.Del(k)
}
encoded := q.Encode()
if encoded == "" {
return r.Url()
}
return r.Url() + "?" + encoded
}
// HasHeader checks if the request has the specified header.
func (r *Request) HasHeader(key string) bool {
if r.Request == nil {
return false
}
return r.Request.Header.Get(key) != ""
}
// IsJson checks if the request's Content-Type indicates JSON.
func (r *Request) IsJson() bool {
ct := r.Header("Content-Type")