-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcoverage.html
3109 lines (2642 loc) · 130 KB
/
coverage.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>quick: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/jeffotoni/quick/ctx.go (82.4%)</option>
<option value="file1">github.com/jeffotoni/quick/group.go (82.1%)</option>
<option value="file2">github.com/jeffotoni/quick/http.status.go (100.0%)</option>
<option value="file3">github.com/jeffotoni/quick/quick.go (92.8%)</option>
<option value="file4">github.com/jeffotoni/quick/quick_ctx_mock.go (100.0%)</option>
<option value="file5">github.com/jeffotoni/quick/quick_pool.go (93.5%)</option>
<option value="file6">github.com/jeffotoni/quick/quick_upload_file.go (91.9%)</option>
<option value="file7">github.com/jeffotoni/quick/quicktest.go (87.1%)</option>
<option value="file8">github.com/jeffotoni/quick/quicktest_v2.go (76.1%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package quick
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
)
type Ctx struct {
Response http.ResponseWriter
Request *http.Request
resStatus int
MoreRequests int
bodyByte []byte
JsonStr string
Headers map[string][]string
Params map[string]string
Query map[string]string
uploadFileSize int64 // Upload limit in bytes
}
func (c *Ctx) SetStatus(status int) <span class="cov0" title="0">{
c.resStatus = status
}</span>
// UploadedFile holds details of an uploaded file.
type UploadedFile struct {
File multipart.File
Multipart *multipart.FileHeader
Info FileInfo
}
// FileInfo contains metadata of the uploaded file.
type FileInfo struct {
Filename string
Size int64
ContentType string
Bytes []byte
}
// GetReqHeadersAll returns all the request headers
// The result will GetReqHeadersAll() map[string][]string
func (c *Ctx) GetReqHeadersAll() map[string][]string <span class="cov8" title="1">{
return c.Headers
}</span>
// GetHeadersAll returns all HTTP response headers stored in the context
// The result will GetHeadersAll() map[string][]string
func (c *Ctx) GetHeadersAll() map[string][]string <span class="cov8" title="1">{
return c.Headers
}</span>
// Http serveFile send specific file
// The result will File(filePath string)
func (c *Ctx) File(filePath string) error <span class="cov8" title="1">{
filePath = strings.TrimSuffix(filePath, "/*")
if stat, err := os.Stat(filePath); err == nil && stat.IsDir() </span><span class="cov8" title="1">{
filePath = filepath.Join(filePath, "index.html")
}</span>
<span class="cov8" title="1">http.ServeFile(c.Response, c.Request, filePath)
return nil</span>
}
// Bind analyzes and links the request body to a Go structure
// The result will Bind(v interface{}) (err error)
func (c *Ctx) Bind(v interface{}) (err error) <span class="cov8" title="1">{
return extractParamsBind(c, v)
}</span>
// BodyParser efficiently unmarshals the request body into the provided struct (v) based on the Content-Type header.
//
// Supported content-types:
// - application/json
// - application/xml, text/xml
//
// Parameters:
// - v: The target structure to decode the request body into.
//
// Returns:
// - error: An error if decoding fails or if the content-type is unsupported.
func (c *Ctx) BodyParser(v interface{}) error <span class="cov8" title="1">{
contentType := strings.ToLower(c.Request.Header.Get("Content-Type"))
switch </span>{
case strings.HasPrefix(contentType, ContentTypeAppJSON):<span class="cov8" title="1">
return json.Unmarshal(c.bodyByte, v)</span>
case strings.Contains(contentType, ContentTypeAppXML),
strings.Contains(contentType, ContentTypeTextXML):<span class="cov0" title="0">
return xml.Unmarshal(c.bodyByte, v)</span>
default:<span class="cov0" title="0">
return fmt.Errorf("unsupported content-type: %s", contentType)</span>
}
}
// Param returns the value of the URL parameter corresponding to the given key
// The result will Param(key string) string
func (c *Ctx) Param(key string) string <span class="cov8" title="1">{
val, ok := c.Params[key]
if ok </span><span class="cov8" title="1">{
return val
}</span>
<span class="cov0" title="0">return ""</span>
}
// Body returns the request body as a byte slice ([]byte)
// The result will Body() []byte
func (c *Ctx) Body() []byte <span class="cov8" title="1">{
return c.bodyByte
}</span>
// BodyString returns the request body as a string
// The result will BodyString() string
func (c *Ctx) BodyString() string <span class="cov8" title="1">{
return string(c.bodyByte)
}</span>
// JSON encodes the provided interface (v) as JSON, sets the Content-Type header,
// and writes the response efficiently using buffer pooling.
//
// Parameters:
// - v: The data structure to encode as JSON.
//
// Returns:
// - error: An error if JSON encoding fails or if writing the response fails.
func (c *Ctx) JSON(v interface{}) error <span class="cov8" title="1">{
buf := acquireJSONBuffer()
defer releaseJSONBuffer(buf)
if err := json.NewEncoder(buf).Encode(v); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">if buf.Len() > 0 && buf.Bytes()[buf.Len()-1] == '\n' </span><span class="cov8" title="1">{
buf.Truncate(buf.Len() - 1)
}</span>
<span class="cov8" title="1">c.writeResponse(buf.Bytes())
return nil</span>
}
// JSONIN encodes the given interface as JSON with indentation and writes it to the HTTP response.
// Allows optional parameters to define the indentation format.
//
// ATTENTION
// use only for debugging, very slow
//
// Parameters:
// - v: The data structure to encode as JSON.
// - params (optional): Defines the indentation settings.
// - If params[0] is provided, it will be used as the prefix.
// - If params[1] is provided, it will be used as the indentation string.
//
// Returns:
// - error: An error if JSON encoding fails or if writing to the ResponseWriter fails.
func (c *Ctx) JSONIN(v interface{}, params ...string) error <span class="cov8" title="1">{
// Default indentation settings
prefix := ""
indent := " " // Default to 2 spaces
// Override if parameters are provided
if len(params) > 0 </span><span class="cov0" title="0">{
prefix = params[0]
}</span>
<span class="cov8" title="1">if len(params) > 1 </span><span class="cov0" title="0">{
indent = params[1]
}</span>
<span class="cov8" title="1">buf := acquireJSONBuffer()
defer releaseJSONBuffer(buf)
// Exemplo com JSON:
enc := json.NewEncoder(buf)
enc.SetIndent(prefix, indent)
if buf.Len() > 0 && buf.Bytes()[buf.Len()-1] == '\n' </span><span class="cov0" title="0">{
buf.Truncate(buf.Len() - 1)
}</span>
<span class="cov8" title="1">if err := enc.Encode(v); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">c.writeResponse(buf.Bytes())
return nil</span>
}
// XML serializes the given value to XML and writes it to the HTTP response.
// It avoids unnecessary memory allocations by using buffer pooling and ensures that no extra newline is appended.
//
// Parameters:
// - v: The data structure to encode as XML.
//
// Returns:
// - error: An error if XML encoding fails or if writing to the ResponseWriter fails.
func (c *Ctx) XML(v interface{}) error <span class="cov8" title="1">{
buf := acquireXMLBuffer()
defer releaseXMLBuffer(buf)
if err := xml.NewEncoder(buf).Encode(v); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">if buf.Len() > 0 && buf.Bytes()[buf.Len()-1] == '\n' </span><span class="cov0" title="0">{
buf.Truncate(buf.Len() - 1)
}</span>
<span class="cov8" title="1">c.writeResponse(buf.Bytes())
return nil</span>
}
// writeResponse writes the provided byte content to the ResponseWriter.
//
// If a custom status code (resStatus) has been set, it writes the header before the body.
//
// Parameters:
// - b: The byte slice to be written in the HTTP response.
//
// Returns:
// - error: An error if writing to the ResponseWriter fails.
func (c *Ctx) writeResponse(b []byte) error <span class="cov8" title="1">{
if c.Response == nil </span><span class="cov0" title="0">{
return errors.New("nil response writer")
}</span>
<span class="cov8" title="1">if c.resStatus == 0 </span><span class="cov8" title="1">{
c.resStatus = http.StatusOK
}</span>
<span class="cov8" title="1">c.Response.WriteHeader(c.resStatus)
_, err := c.Response.Write(b)
if flusher, ok := c.Response.(http.Flusher); ok </span><span class="cov8" title="1">{
flusher.Flush()
}</span>
<span class="cov8" title="1">return err</span>
}
// Byte writes an array of bytes to the HTTP response, using writeResponse()
// The result will Byte(b []byte) (err error)
func (c *Ctx) Byte(b []byte) (err error) <span class="cov8" title="1">{
return c.writeResponse(b)
}</span>
// Send writes a byte array to the HTTP response, using writeResponse()
// The result will Send(b []byte) (err error)
func (c *Ctx) Send(b []byte) (err error) <span class="cov8" title="1">{
return c.writeResponse(b)
}</span>
// SendString writes a string in the HTTP response, converting it to an array of bytes and using writeResponse()
// The result will SendString(s string) error
func (c *Ctx) SendString(s string) error <span class="cov8" title="1">{
return c.writeResponse([]byte(s))
}</span>
// String escreve uma string na resposta HTTP, convertendo-a para um array de bytes e utilizando writeResponse()
// The result will String(s string) error
func (c *Ctx) String(s string) error <span class="cov8" title="1">{
return c.writeResponse([]byte(s))
}</span>
// SendFile writes a file in the HTTP response as an array of bytes
// The result will SendFile(file []byte) error
func (c *Ctx) SendFile(file []byte) error <span class="cov8" title="1">{
_, err := c.Response.Write(file)
return err
}</span>
// Set defines an HTTP header in the response
// The result will Set(key, value string)
func (c *Ctx) Set(key, value string) <span class="cov8" title="1">{
c.Response.Header().Set(key, value)
}</span>
// Append adds a value to the HTTP header specified in the response
// The result will Append(key, value string)
func (c *Ctx) Append(key, value string) <span class="cov8" title="1">{
c.Response.Header().Add(key, value)
}</span>
// Accepts defines the HTTP header "Accept" in the response
// The result will Accepts(acceptType string) *Ctx
func (c *Ctx) Accepts(acceptType string) *Ctx <span class="cov8" title="1">{
c.Response.Header().Set("Accept", acceptType)
return c
}</span>
// Status defines the HTTP status code of the response
// The result will Status(status int) *Ctx
func (c *Ctx) Status(status int) *Ctx <span class="cov8" title="1">{
c.resStatus = status
return c
}</span>
//MultipartForm
// FormFileLimit sets the maximum allowed upload size.
func (c *Ctx) FormFileLimit(limit string) error <span class="cov8" title="1">{
size, err := parseSize(limit)
if err != nil </span><span class="cov8" title="1">{
return err
}</span>
<span class="cov8" title="1">c.uploadFileSize = size
return nil</span>
}
// FormFile processes an uploaded file and returns its details.
// The result will FormFile(fieldName string) (*UploadedFile, error)
func (c *Ctx) FormFile(fieldName string) (*UploadedFile, error) <span class="cov8" title="1">{
files, err := c.FormFiles(fieldName)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">if len(files) == 0 </span><span class="cov0" title="0">{
return nil, errors.New("no file uploaded")
}</span>
<span class="cov8" title="1">return files[0], nil</span> // Return the first file if multiple are uploaded
}
// fileWrapper, which wraps a bytes.Reader and adds the Close() method,
// allowing it to be treated as an io.ReadCloser.
// We ensure that the file can be read multiple times without losing data.
// fileWrapper supports multipart.File.
type fileWrapper struct {
*bytes.Reader
}
// There is nothing to close as we are reading from memory
func (fw *fileWrapper) Close() error <span class="cov0" title="0">{
return nil
}</span>
// FormFiles processes an uploaded file and returns its details.
// The result will FormFiles(fieldName string) (*UploadedFile, error)
func (c *Ctx) FormFiles(fieldName string) ([]*UploadedFile, error) <span class="cov8" title="1">{
if c.uploadFileSize == 0 </span><span class="cov8" title="1">{
c.uploadFileSize = 1 << 20 // set default 1MB
}</span>
// check request
<span class="cov8" title="1">if c.Request == nil </span><span class="cov8" title="1">{
return nil, errors.New("HTTP request is nil")
}</span>
// check body
<span class="cov8" title="1">if c.Request.Body == nil </span><span class="cov0" title="0">{
return nil, errors.New("request body is nil")
}</span>
// check if `Content-Type` this ok
<span class="cov8" title="1">contentType := c.Request.Header.Get("Content-Type")
if !strings.HasPrefix(contentType, "multipart/form-data") </span><span class="cov0" title="0">{
return nil, errors.New("invalid content type, expected multipart/form-data")
}</span>
// Parse multipart form with the defined limit
<span class="cov8" title="1">if err := c.Request.ParseMultipartForm(c.uploadFileSize); err != nil </span><span class="cov0" title="0">{
return nil, errors.New("failed to parse multipart form: " + err.Error())
}</span>
// Debugging: Check if files exist
<span class="cov8" title="1">if c.Request.MultipartForm == nil || c.Request.MultipartForm.File[fieldName] == nil </span><span class="cov8" title="1">{
return nil, errors.New("no files found in the request")
}</span>
// Retrieve all files for the given field name
<span class="cov8" title="1">files := c.Request.MultipartForm.File[fieldName]
if len(files) == 0 </span><span class="cov0" title="0">{
return nil, errors.New("no files found for field: " + fieldName)
}</span>
<span class="cov8" title="1">var uploadedFiles []*UploadedFile
for _, handler := range files </span><span class="cov8" title="1">{
// Open file
file, err := handler.Open()
if err != nil </span><span class="cov0" title="0">{
return nil, errors.New("failed to open file: " + err.Error())
}</span>
<span class="cov8" title="1">defer file.Close()
// Read file content into memory
var buf bytes.Buffer
if _, err := io.Copy(&buf, file); err != nil </span><span class="cov0" title="0">{
return nil, errors.New("failed to read file into buffer")
}</span>
// reset multipart.File
// Create a reusable copy of the file
// that implements multipart.File correctly
<span class="cov8" title="1">fileCopy := &fileWrapper{bytes.NewReader(buf.Bytes())}
// Detect content type
contentType := http.DetectContentType(buf.Bytes())
// Append file details
uploadedFiles = append(uploadedFiles, &UploadedFile{
File: fileCopy,
Multipart: handler,
Info: FileInfo{
Filename: handler.Filename,
Size: handler.Size,
ContentType: contentType,
Bytes: buf.Bytes(),
},
})</span>
}
<span class="cov8" title="1">return uploadedFiles, nil</span>
}
// MultipartForm allows access to the raw multipart form data (for advanced users)
// The result will MultipartForm() (*multipart.Form, error)
func (c *Ctx) MultipartForm() (*multipart.Form, error) <span class="cov8" title="1">{
if err := c.Request.ParseMultipartForm(c.uploadFileSize); err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">return c.Request.MultipartForm, nil</span>
}
// FormValue retrieves a form value by key.
// It automatically calls ParseForm() before accessing the value.
// The result will FormValue(key string) string
func (c *Ctx) FormValue(key string) string <span class="cov8" title="1">{
// Checks if the Content-Type is multipart
if c.Request.Header.Get("Content-Type") == "multipart/form-data" </span><span class="cov0" title="0">{
_ = c.Request.ParseMultipartForm(c.uploadFileSize) // Force correct processing
}</span> else<span class="cov8" title="1"> {
_ = c.Request.ParseForm() // For application/x-www-form-urlencoded
}</span>
<span class="cov8" title="1">return c.Request.FormValue(key)</span>
}
// FormValues returns all form values as a map.
// It automatically calls ParseForm() before accessing the values.
// The result will FormValues() map[string][]string
func (c *Ctx) FormValues() map[string][]string <span class="cov8" title="1">{
// Checks if the Content-Type is multipart
if c.Request.Header.Get("Content-Type") == "multipart/form-data" </span><span class="cov0" title="0">{
_ = c.Request.ParseMultipartForm(c.uploadFileSize) // Required to process multipart
}</span> else<span class="cov8" title="1"> {
_ = c.Request.ParseForm() // Processes application/x-www-form-urlencoded
}</span>
<span class="cov8" title="1">return c.Request.Form</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package quick
import (
"net/http"
"strings"
"github.com/jeffotoni/quick/internal/concat"
)
// Constants for route processing
const (
methodSeparator = "#"
errInvalidExtractor = "Invalid function signature for paramExtractor"
)
// Group represents a collection of routes that share a common prefix
type Group struct {
prefix string
routes []Route
middlewares []func(http.Handler) http.Handler
quick *Quick
}
// Use adds middlewares to the group
// The result will Use(mw func(http.Handler) http.Handler)
func (g *Group) Use(mw func(http.Handler) http.Handler) <span class="cov0" title="0">{
g.middlewares = append(g.middlewares, mw)
}</span>
// Group creates a new route group with a shared prefix
// The result will Group(prefix string) *Group
func (q *Quick) Group(prefix string) *Group <span class="cov8" title="1">{
g := &Group{
prefix: prefix,
routes: []Route{},
quick: q,
}
q.groups = append(q.groups, *g)
return g
}</span>
// normalizePattern constructs the full path with the group prefix
// The result will normalizePattern(prefix, pattern string) string
func normalizePattern(prefix, pattern string) string <span class="cov8" title="1">{
return concat.String(strings.TrimRight(prefix, "/"), "/", strings.TrimLeft(pattern, "/"))
}</span>
// resolveParamExtractor ensures the correct function signature for paramExtractor
// The result will resolveParamExtractor(q *Quick, handlerFunc HandleFunc, paramExtractor interface{}, path, params string) http.HandlerFunc
func resolveParamExtractor(q *Quick, handlerFunc HandleFunc, paramExtractor interface{}, path, params string) http.HandlerFunc <span class="cov8" title="1">{
switch fn := paramExtractor.(type) </span>{
case func(*Quick, HandleFunc) http.HandlerFunc:<span class="cov8" title="1">
return fn(q, handlerFunc)</span>
case func(*Quick, string, string, HandleFunc) http.HandlerFunc:<span class="cov8" title="1">
return fn(q, path, params, handlerFunc)</span>
default:<span class="cov0" title="0">
panic(errInvalidExtractor)</span>
}
}
// applyMiddlewares applies all middlewares to a handler
// The result will applyMiddlewares(handler http.HandlerFunc, middlewares []func(http.Handler) http.Handler) http.HandlerFunc
func applyMiddlewares(handler http.HandlerFunc, middlewares []func(http.Handler) http.Handler) http.HandlerFunc <span class="cov8" title="1">{
for _, mw := range middlewares </span><span class="cov0" title="0">{
handler = mw(handler).(http.HandlerFunc) // CORREÇÃO: Garante conversão correta
}</span>
<span class="cov8" title="1">return handler</span>
}
// createAndRegisterRoute creates a new route and registers it in the Quick router
// The result will createAndRegisterRoute(g *Group, method, pattern, compiledPattern, params string, handler http.HandlerFunc)
func createAndRegisterRoute(g *Group, method, pattern, compiledPattern, params string, handler http.HandlerFunc) <span class="cov8" title="1">{
route := Route{
Pattern: compiledPattern,
Path: pattern,
Params: params,
handler: handler,
Method: method,
Group: g.prefix,
}
g.quick.appendRoute(&route)
// FIX: Adjust path in mux to maintain compatibility with tests
if method == http.MethodGet </span><span class="cov8" title="1">{
g.quick.mux.HandleFunc(pattern, handler)
}</span> else<span class="cov8" title="1"> {
g.quick.mux.HandleFunc(concat.String(strings.ToLower(method), methodSeparator, pattern), handler)
}</span>
}
// Handle registers a new route dynamically
// The result will Handle(method, pattern string, handlerFunc HandleFunc, paramExtractor interface{})
func (g *Group) Handle(method, pattern string, handlerFunc HandleFunc, paramExtractor any) <span class="cov8" title="1">{
// Normalize pattern and extract parameters
pattern = normalizePattern(g.prefix, pattern)
path, params, compiledPattern := extractParamsPattern(pattern)
// Resolve parameter extractor and apply middlewares
handler := resolveParamExtractor(g.quick, handlerFunc, paramExtractor, path, params)
handler = applyMiddlewares(handler, g.middlewares)
// Register route
createAndRegisterRoute(g, method, pattern, compiledPattern, params, handler)
}</span>
// Get registers a new GET route
// The result will Get(pattern string, handlerFunc HandleFunc)
func (g *Group) Get(pattern string, handlerFunc HandleFunc) <span class="cov8" title="1">{
g.Handle(http.MethodGet, pattern, handlerFunc, extractParamsGet)
}</span>
// Post registers a new POST route
// The result will Post(pattern string, handlerFunc HandleFunc)
func (g *Group) Post(pattern string, handlerFunc HandleFunc) <span class="cov8" title="1">{
g.Handle(http.MethodPost, pattern, handlerFunc, extractParamsPost)
}</span>
// Put registers a new PUT route
// The result will Put(pattern string, handlerFunc HandleFunc)
func (g *Group) Put(pattern string, handlerFunc HandleFunc) <span class="cov8" title="1">{
g.Handle(http.MethodPut, pattern, handlerFunc, extractParamsPut)
}</span>
// Delete registers a new DELETE route
// The result will Delete(pattern string, handlerFunc HandleFunc)
func (g *Group) Delete(pattern string, handlerFunc HandleFunc) <span class="cov8" title="1">{
g.Handle(http.MethodDelete, pattern, handlerFunc, extractParamsDelete)
}</span>
// Patch registers a new PATCH route
// The result will Patch(pattern string, handlerFunc HandleFunc)
func (g *Group) Patch(pattern string, handlerFunc HandleFunc) <span class="cov0" title="0">{
g.Handle(http.MethodPatch, pattern, handlerFunc, extractParamsPatch)
}</span>
// Options registers a new OPTIONS route
// The result will Options(pattern string, handlerFunc HandleFunc)
func (g *Group) Options(pattern string, handlerFunc HandleFunc) <span class="cov0" title="0">{
g.Handle(http.MethodOptions, pattern, handlerFunc, extractParamsOptions)
}</span>
</pre>
<pre class="file" id="file2" style="display: none">// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package quick
const (
// MethodGet represents the HTTP GET method.
MethodGet = "GET"
// MethodHead represents the HTTP HEAD method.
MethodHead = "HEAD"
// MethodPost represents the HTTP POST method.
MethodPost = "POST"
// MethodPut represents the HTTP PUT method.
MethodPut = "PUT"
// MethodPatch represents the HTTP PATCH method (RFC 5789).
MethodPatch = "PATCH"
// MethodDelete represents the HTTP DELETE method.
MethodDelete = "DELETE"
// MethodConnect represents the HTTP CONNECT method.
MethodConnect = "CONNECT"
// MethodOptions represents the HTTP OPTIONS method.
MethodOptions = "OPTIONS"
// MethodTrace represents the HTTP TRACE method.
MethodTrace = "TRACE"
)
// HTTP status codes as registered with IANA.
// See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const (
// StatusContinue indicates that the client should continue with its request.
StatusContinue = 100 // RFC 9110, 15.2.1
// StatusSwitchingProtocols indicates that the server is switching protocols as requested.
StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
// StatusProcessing indicates that the server has received the request but has not completed processing.
StatusProcessing = 102 // RFC 2518, 10.1
// StatusEarlyHints provides early hints to help a client start preloading resources.
StatusEarlyHints = 103 // RFC 8297
// StatusOK indicates that the request has succeeded.
StatusOK = 200 // RFC 9110, 15.3.1
// StatusCreated indicates that the request has been fulfilled and a new resource is created.
StatusCreated = 201 // RFC 9110, 15.3.2
// StatusAccepted indicates that the request has been accepted for processing but is not complete.
StatusAccepted = 202 // RFC 9110, 15.3.3
// StatusNonAuthoritativeInfo indicates that the response contains information from another source.
StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
// StatusNoContent indicates that the server successfully processed the request but has no content to return.
StatusNoContent = 204 // RFC 9110, 15.3.5
// StatusResetContent indicates that the client should reset the document view.
StatusResetContent = 205 // RFC 9110, 15.3.6
// StatusPartialContent indicates that only part of the requested resource is returned.
StatusPartialContent = 206 // RFC 9110, 15.3.7
// StatusMultiStatus indicates that multiple status codes might be returned.
StatusMultiStatus = 207 // RFC 4918, 11.1
// StatusAlreadyReported indicates that the request has already been reported in a previous response.
StatusAlreadyReported = 208 // RFC 5842, 7.1
// StatusIMUsed indicates that the response is a result of an instance manipulation.
StatusIMUsed = 226 // RFC 3229, 10.4.1
// StatusMultipleChoices indicates that multiple possible resources could be returned.
StatusMultipleChoices = 300 // RFC 9110, 15.4.1
// StatusMovedPermanently indicates that the resource has moved permanently to a new URI.
StatusMovedPermanently = 301 // RFC 9110, 15.4.2
// StatusFound indicates that the requested resource has been temporarily moved.
StatusFound = 302 // RFC 9110, 15.4.3
// StatusSeeOther indicates that the response is available at a different URI.
StatusSeeOther = 303 // RFC 9110, 15.4.4
// StatusNotModified indicates that the resource has not been modified since the last request.
StatusNotModified = 304 // RFC 9110, 15.4.5
// StatusUseProxy indicates that the requested resource must be accessed through a proxy.
StatusUseProxy = 305 // RFC 9110, 15.4.6
// 306 Unused (was previously defined in an earlier version of the HTTP specification).
_ = 306 // RFC 9110, 15.4.7 (Unused)
// StatusTemporaryRedirect indicates that the request should be repeated with a different URI.
StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
// StatusPermanentRedirect indicates that the resource has been permanently moved.
StatusPermanentRedirect = 308 // RFC 9110, 15.4.9
// StatusBadRequest indicates that the server cannot process the request due to client error.
StatusBadRequest = 400 // RFC 9110, 15.5.1
// StatusUnauthorized indicates that authentication is required and has failed or not been provided.
StatusUnauthorized = 401 // RFC 9110, 15.5.2
// StatusPaymentRequired is reserved for future use (typically related to digital payments).
StatusPaymentRequired = 402 // RFC 9110, 15.5.3
// StatusForbidden indicates that the request is valid, but the server is refusing to process it.
StatusForbidden = 403 // RFC 9110, 15.5.4
// StatusNotFound indicates that the requested resource could not be found.
StatusNotFound = 404 // RFC 9110, 15.5.5
// StatusMethodNotAllowed indicates that the request method is not allowed for the resource.
StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6
// StatusNotAcceptable indicates that the server cannot return a response that meets the client's requirements.
StatusNotAcceptable = 406 // RFC 9110, 15.5.7
// StatusProxyAuthRequired indicates that authentication is required for a proxy server.
StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8
// StatusRequestTimeout indicates that the server timed out waiting for the request.
StatusRequestTimeout = 408 // RFC 9110, 15.5.9
// StatusConflict indicates that the request could not be completed due to a conflict with the current resource state.
StatusConflict = 409 // RFC 9110, 15.5.10
// StatusGone indicates that the requested resource is no longer available and will not return.
StatusGone = 410 // RFC 9110, 15.5.11
// StatusLengthRequired indicates that the request must include a valid `Content-Length` header.
StatusLengthRequired = 411 // RFC 9110, 15.5.12
// StatusPreconditionFailed indicates that a precondition in the request headers was not met.
StatusPreconditionFailed = 412 // RFC 9110, 15.5.13
// StatusRequestEntityTooLarge indicates that the request body is too large for the server to process.
StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14
// StatusRequestURITooLong indicates that the request URI is too long for the server to process.
StatusRequestURITooLong = 414 // RFC 9110, 15.5.15
// StatusUnsupportedMediaType indicates that the request body format is not supported by the server.
StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16
// StatusRequestedRangeNotSatisfiable indicates that the range specified in the request cannot be fulfilled.
StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
// StatusExpectationFailed indicates that the server cannot meet the expectations set in the request headers.
StatusExpectationFailed = 417 // RFC 9110, 15.5.18
// StatusTeapot is an Easter egg from RFC 9110, originally from April Fools' Day (RFC 2324).
StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused)
// StatusMisdirectedRequest indicates that the request was directed to a server that cannot respond appropriately.
StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20
// StatusUnprocessableEntity indicates that the request was well-formed but contains semantic errors.
StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21
// StatusLocked indicates that the requested resource is currently locked.
StatusLocked = 423 // RFC 4918, 11.3
// StatusFailedDependency indicates that the request failed due to a failed dependency.
StatusFailedDependency = 424 // RFC 4918, 11.4
// StatusTooEarly indicates that the request was sent too early and should be retried later.
StatusTooEarly = 425 // RFC 8470, 5.2.
// StatusUpgradeRequired indicates that the client should switch to a different protocol (e.g., HTTPS).
StatusUpgradeRequired = 426 // RFC 9110, 15.5.22
// StatusPreconditionRequired indicates that a precondition header is required for the request.
StatusPreconditionRequired = 428 // RFC 6585, 3
// StatusTooManyRequests indicates that the client has sent too many requests in a given period.
StatusTooManyRequests = 429 // RFC 6585, 4
// StatusRequestHeaderFieldsTooLarge indicates that the request headers are too large for the server to process.
StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
// StatusUnavailableForLegalReasons indicates that the resource is unavailable for legal reasons (e.g., censorship).
StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
// StatusInternalServerError indicates that the server encountered an unexpected condition.
StatusInternalServerError = 500 // RFC 9110, 15.6.1
// StatusNotImplemented indicates that the server does not support the requested functionality.
StatusNotImplemented = 501 // RFC 9110, 15.6.2
// StatusBadGateway indicates that the server, acting as a gateway or proxy, received an invalid response.
StatusBadGateway = 502 // RFC 9110, 15.6.3
// StatusServiceUnavailable indicates that the server is temporarily unable to handle the request (e.g., overloaded or under maintenance).
StatusServiceUnavailable = 503 // RFC 9110, 15.6.4
// StatusGatewayTimeout indicates that the server, acting as a gateway or proxy, did not receive a timely response.
StatusGatewayTimeout = 504 // RFC 9110, 15.6.5
// StatusHTTPVersionNotSupported indicates that the server does not support the HTTP version used in the request.
StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.6.6
// StatusVariantAlsoNegotiates indicates that the server has an internal configuration error preventing negotiation.
StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
// StatusInsufficientStorage indicates that the server cannot store the representation needed to complete the request.
StatusInsufficientStorage = 507 // RFC 4918, 11.5
// StatusLoopDetected indicates that the server detected an infinite loop while processing the request.
StatusLoopDetected = 508 // RFC 5842, 7.2
// StatusNotExtended indicates that further extensions to the request are required for the server to fulfill it.
StatusNotExtended = 510 // RFC 2774, 7
// StatusNetworkAuthenticationRequired indicates that the client must authenticate to gain network access.
StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)
// StatusText returns a text for the HTTP status code. It returns the empty
// string if the code is unknown.
func StatusText(code int) string <span class="cov8" title="1">{
switch code </span>{
case StatusContinue:<span class="cov8" title="1">
return "Continue"</span>
case StatusSwitchingProtocols:<span class="cov8" title="1">
return "Switching Protocols"</span>
case StatusProcessing:<span class="cov8" title="1">
return "Processing"</span>
case StatusEarlyHints:<span class="cov8" title="1">
return "Early Hints"</span>
case StatusOK:<span class="cov8" title="1">
return "OK"</span>
case StatusCreated:<span class="cov8" title="1">
return "Created"</span>
case StatusAccepted:<span class="cov8" title="1">
return "Accepted"</span>
case StatusNonAuthoritativeInfo:<span class="cov8" title="1">
return "Non-Authoritative Information"</span>
case StatusNoContent:<span class="cov8" title="1">
return "No Content"</span>
case StatusResetContent:<span class="cov8" title="1">
return "Reset Content"</span>
case StatusPartialContent:<span class="cov8" title="1">
return "Partial Content"</span>
case StatusMultiStatus:<span class="cov8" title="1">
return "Multi-Status"</span>
case StatusAlreadyReported:<span class="cov8" title="1">
return "Already Reported"</span>
case StatusIMUsed:<span class="cov8" title="1">
return "IM Used"</span>
case StatusMultipleChoices:<span class="cov8" title="1">
return "Multiple Choices"</span>
case StatusMovedPermanently:<span class="cov8" title="1">
return "Moved Permanently"</span>
case StatusFound:<span class="cov8" title="1">
return "Found"</span>
case StatusSeeOther:<span class="cov8" title="1">
return "See Other"</span>
case StatusNotModified:<span class="cov8" title="1">
return "Not Modified"</span>
case StatusUseProxy:<span class="cov8" title="1">
return "Use Proxy"</span>
case StatusTemporaryRedirect:<span class="cov8" title="1">
return "Temporary Redirect"</span>
case StatusPermanentRedirect:<span class="cov8" title="1">
return "Permanent Redirect"</span>
case StatusBadRequest:<span class="cov8" title="1">
return "Bad Request"</span>
case StatusUnauthorized:<span class="cov8" title="1">
return "Unauthorized"</span>
case StatusPaymentRequired:<span class="cov8" title="1">
return "Payment Required"</span>
case StatusForbidden:<span class="cov8" title="1">
return "Forbidden"</span>
case StatusNotFound:<span class="cov8" title="1">
return "Not Found"</span>
case StatusMethodNotAllowed:<span class="cov8" title="1">
return "Method Not Allowed"</span>
case StatusNotAcceptable:<span class="cov8" title="1">
return "Not Acceptable"</span>
case StatusProxyAuthRequired:<span class="cov8" title="1">
return "Proxy Authentication Required"</span>
case StatusRequestTimeout:<span class="cov8" title="1">
return "Request Timeout"</span>
case StatusConflict:<span class="cov8" title="1">
return "Conflict"</span>
case StatusGone:<span class="cov8" title="1">
return "Gone"</span>
case StatusLengthRequired:<span class="cov8" title="1">
return "Length Required"</span>
case StatusPreconditionFailed:<span class="cov8" title="1">
return "Precondition Failed"</span>
case StatusRequestEntityTooLarge:<span class="cov8" title="1">
return "Request Entity Too Large"</span>
case StatusRequestURITooLong:<span class="cov8" title="1">
return "Request URI Too Long"</span>
case StatusUnsupportedMediaType:<span class="cov8" title="1">
return "Unsupported Media Type"</span>
case StatusRequestedRangeNotSatisfiable:<span class="cov8" title="1">