-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathquick.go
1948 lines (1751 loc) · 66.8 KB
/
quick.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
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
/*
🚀 Quick is a flexible and extensible route manager for the Go language.
It aims to be fast and performant, and 100% net/http compatible.
Quick is a project under constant development and is open for collaboration,
everyone is welcome to contribute. 😍
*/
package quick
import (
"bytes"
"context"
"crypto/tls"
"embed"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptest"
"os/signal"
"path"
"regexp"
"runtime"
"runtime/debug"
"strings"
"sync"
"syscall"
"time"
"github.com/jeffotoni/quick/internal/concat"
"github.com/jeffotoni/quick/template"
)
// SO_REUSEPORT is a constant manually defined for Linux systems
const SO_REUSEPORT = 0x0F
// Content-Type constants used for response headers
const (
ContentTypeAppJSON = `application/json`
ContentTypeAppXML = `application/xml`
ContentTypeTextXML = `text/xml`
)
// contextKey is a custom type used for storing values in context
type contextKey int
// myContextKey is a predefined key used for context storage
const myContextKey contextKey = 0
// HandleFunc represents a function signature for route handlers in Quick.
//
// This function type is used for defining request handlers within Quick's
// routing system. It receives a pointer to `Ctx`, which encapsulates
// request and response data.
//
// Example Usage:
//
// q.Get("/example", func(c *quick.Ctx) error {
// return c.Status(quick.StatusOK).SendString("Hello, Quick!")
// })
type HandleFunc func(*Ctx) error
// nextFunc is an internal type used to control next handler execution.
type nextFunc func(*Ctx) error
// HandlerFunc defines the function signature for request handlers in Quick.
//
// This type provides a way to implement request handlers as standalone
// functions while still conforming to the `Handler` interface. It allows
// functions of type `HandlerFunc` to be passed as middleware or endpoint handlers.
//
// Example Usage:
//
// func myHandler(c *quick.Ctx) error {
// return c.Status(quick.StatusOK).SendString("HandlerFunc example")
// }
//
// q.Use(quick.HandlerFunc(myHandler))
type HandlerFunc func(c *Ctx) error
// M is a shortcut for map[string]interface{}, allowing `c.M{}`
type M map[string]interface{}
// Handler defines an interface that wraps the ServeQuick method.
//
// Any type implementing `ServeQuick(*Ctx) error` can be used as a request
// handler in Quick. This abstraction allows for more flexible middleware
// and handler implementations, including struct-based handlers.
//
// Example Usage:
//
// type MyHandler struct{}
//
// func (h MyHandler) ServeQuick(c *quick.Ctx) error {
// return c.Status(quick.StatusOK).SendString("Struct-based handler")
// }
//
// q.Use(MyHandler{})
type Handler interface {
// ServeQuick processes an HTTP request in the Quick framework.
//
// Parameters:
// - c *Ctx: The request context containing request and response details.
//
// Returns:
// - error: Any error encountered while processing the request.
ServeQuick(*Ctx) error
}
// ServeQuick allows a HandlerFunc to satisfy the Handler interface.
//
// This method enables `HandlerFunc` to be used wherever a `Handler`
// is required by implementing the `ServeQuick` method.
//
// Example Usage:
//
// q.Use(quick.HandlerFunc(func(c *quick.Ctx) error {
// return c.Status(quick.StatusOK).SendString("Hello from HandlerFunc!")
// }))
func (h HandlerFunc) ServeQuick(c *Ctx) error {
return h(c)
}
// allMethods lists all supported HTTP methods used by the Any method.
var allMethods = []string{
MethodGet,
MethodPost,
MethodPut,
MethodPatch,
MethodDelete,
MethodOptions,
MethodHead,
}
// Any registers the same handlerFunc for all standard HTTP methods (GET, POST, PUT, etc.).
//
// This is useful when you want to attach a single handler to a path regardless of the HTTP method,
// and handle method-based logic inside the handler itself (e.g., returning 405 if not GET).
//
// Example:
//
// app := quick.New()
// app.Any("/health", func(c *quick.Ctx) error {
// if c.Method() != quick.MethodGet {
// return c.Status(quick.StatusMethodNotAllowed).SendString("Method Not Allowed")
// }
// return c.Status(quick.StatusOK).SendString("OK")
// })
//
// Note: The handlerFunc will be registered individually for each method listed in allMethods.
func (q *Quick) Any(path string, handlerFunc HandleFunc) {
for _, method := range allMethods {
q.registerRoute(method, path, handlerFunc)
}
}
// MaxBytesReader is a thin wrapper around http.MaxBytesReader to limit the
// size of the request body in Quick applications.
//
// It returns an io.ReadCloser that reads from r but stops with an error
// after n bytes. The sink just sees an io.EOF.
//
// This is useful to protect against large request bodies.
//
// Example usage:
//
// c.Request.Body = quick.MaxBytesReader(c.Response, c.Request.Body, 10_000) // 10KB
func MaxBytesReader(w http.ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser {
// Internally, just call the standard library function.
return http.MaxBytesReader(w, r, n)
}
// Route represents a registered HTTP route in the Quick framework
type Route struct {
Group string // Route group for organization
Pattern string // URL pattern associated with the route
Path string // The registered path for the route
Params string // Parameters extracted from the URL
Method string // HTTP method associated with the route (GET, POST, etc.)
handler http.HandlerFunc // Handler function for processing the request
}
// ctxServeHttp represents the structure for handling HTTP requests
type ctxServeHttp struct {
Path string // Requested URL path
Params string // Query parameters from the request
Method string // HTTP method of the request
ParamsMap map[string]string // Parsed parameters mapped as key-value pairs
}
// Config defines various configuration options for the Quick server
type Config struct {
BodyLimit int64 // Deprecated: Use MaxBodySize instead
MaxBodySize int64 // Maximum request body size allowed.
MaxHeaderBytes int // Maximum number of bytes allowed in the HTTP headers.
GOMAXPROCS int // defines the maximum number of CPU cores
GCHeapThreshold int64 // GCHeapThreshold sets the memory threshold (in bytes)
BufferPoolSize int // BufferPoolSize determines the size (in bytes)
RouteCapacity int // Initial capacity of the route slice.
MoreRequests int // Value to set GCPercent. influences the garbage collector performance. 0-1000
ReadTimeout time.Duration // Maximum duration for reading the entire request.
WriteTimeout time.Duration // Maximum duration before timing out writes of the response.
IdleTimeout time.Duration // Maximum amount of time to wait for the next request when keep-alives are enabled.
ReadHeaderTimeout time.Duration // Amount of time allowed to read request headers.
GCPercent int // Renamed to be more descriptive (0-1000) - influences the garbage collector performance.
TLSConfig *tls.Config // Integrated TLS configuration
CorsConfig *CorsConfig // Specific type for CORS
Views template.TemplateEngine
NoBanner bool // Flag to disable the Quick startup Display.
}
// defaultConfig defines the default values for the Quick server configuration
var defaultConfig = Config{
BodyLimit: 2 * 1024 * 1024, // Deprecated: Use MaxBodySize instead
MaxBodySize: 2 * 1024 * 1024, // 2MB max request body size
MaxHeaderBytes: 1 * 1024 * 1024, // 1MB max header size
GOMAXPROCS: runtime.NumCPU(), // Use all available CPU cores
GCHeapThreshold: 1 << 30, // 1GB memory threshold for GC
BufferPoolSize: 32768, // Buffer pool size
RouteCapacity: 1000, // Default initial route capacity
MoreRequests: 290, // Default GC value
NoBanner: false, // Show Quick banner by default
}
// Zeroth is a custom type for zero-value constants
type Zeroth int
// Zero is a predefined constant of type Zeroth
const (
Zero Zeroth = 0
)
// CorsConfig defines the CORS settings for Quick
type CorsConfig struct {
Enabled bool // If true, enables CORS support
Options map[string]string // Custom CORS options
AllowAll bool // If true, allows all origins
}
// Quick is the main structure of the framework, holding routes and configurations.
type Quick struct {
config Config // Configuration settings.
Cors bool // Indicates if CORS is enabled.
groups []Group // List of route groups.
handler http.Handler // The primary HTTP handler.
mux *http.ServeMux // Multiplexer for routing requests.
routes []*Route // Registered routes.
routeCapacity int // The maximum number of routes allowed.
mws2 []any // List of registered middlewares.
CorsSet func(http.Handler) http.Handler // CORS middleware handler function.
CorsOptions map[string]string // CORS options map
// corsConfig *CorsConfig // Specific type for CORS // Removed unused field
embedFS embed.FS // File system for embedded static files.
server *http.Server // Http server
bufferPool *sync.Pool // Reusable buffer pool to reduce allocations and improve performance
}
// indeed to Quick
type App = Quick
// (q *Quick) Config() Config
//
// example: c.App.GetConfig().Views
func (q *Quick) GetConfig() Config {
return q.config
}
// HandlerFunc adapts a quick.HandlerFunc to a standard http.HandlerFunc.
// It creates a new Quick context (Ctx) for each HTTP request,
// allowing Quick handlers to access request and response objects seamlessly.
//
// Usage Example:
//
// http.HandleFunc(\"/\", app.HandlerFunc(func(c *quick.Ctx) error {
// return c.Status(200).JSON(map[string]string{\"message\": \"Hello, Quick!\"})
// }))
func (q *Quick) HandlerFunc(h HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
c := &Ctx{
Response: w,
Request: req,
App: q,
}
if err := h(c); err != nil {
http.Error(w, err.Error(), StatusInternalServerError)
}
}
}
// Handler returns the main HTTP handler for Quick, allowing integration with standard http.Server and testing frameworks.
func (q *Quick) Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q.ServeHTTP(w, r)
})
}
// MiddlewareFunc defines the signature for middleware functions in Quick.
// A middleware function receives the next HandlerFunc in the chain and returns a new HandlerFunc.
// Middleware can perform actions before and/or after calling the next handler.
//
// Example:
//
// func LoggingMiddleware() quick.MiddlewareFunc {
// return func(next quick.HandlerFunc) quick.HandlerFunc {
// return func(c *quick.Ctx) error {
// // Before handler logic (e.g., logging request details)
// log.Printf("Request received: %s %s", c.Request.Method, c.Request.URL)
//
// err := next(c) // Call the next handler
//
// // After handler logic (e.g., logging response status)
// log.Printf("Response sent with status: %d", c.ResponseWriter.Status())
//
// return err
// }
// }
// }
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
// GetDefaultConfig returns the default configuration pre-defined for the system.
//
// This function provides a standardized configuration setup, ensuring that
// new instances use a consistent and optimized set of defaults.
//
// Returns:
// - Config: A struct containing the default system configuration.
//
// Example Usage:
//
// // This function is typically used when initializing a new Quick instance
// // to ensure it starts with the default settings if no custom config is provided.
func GetDefaultConfig() Config {
return defaultConfig
}
// New creates a new instance of the Quick structure to manage HTTP routes and handlers.
//
// This function initializes a Quick instance with optional configurations provided
// through the `Config` parameter. If no configuration is provided, it uses the `defaultConfig`.
//
// Parameters:
// - c ...Config: (Optional) Configuration settings for customizing the Quick instance.
//
// Returns:
// - *Quick: A pointer to the initialized Quick instance.
//
// Example Usage:
//
// // Basic usage - Create a default Quick instance
// q := quick.New()
//
// // Custom usage - Create a Quick instance with specific configurations
// q := quick.New(quick.Config{
// RouteCapacity: 500,
// })
//
// q.Get("/", func(c quick.Ctx) error {
// return c.SendString("Hello, Quick!")
// })
func New(c ...Config) *Quick {
var config Config
// Check if a custom configuration is provided
if len(c) > 0 {
config = c[0] // Use the provided configuration
} else {
config = defaultConfig // Use the default configuration
}
// Ensure a minimum route capacity if not set
if config.RouteCapacity == 0 {
config.RouteCapacity = 1000
}
// Initialize and return the Quick instance
return &Quick{
routes: make([]*Route, 0, config.RouteCapacity),
routeCapacity: config.RouteCapacity,
mux: http.NewServeMux(),
handler: http.NewServeMux(),
config: config,
}
}
// Use function adds middleware to the Quick server, with special treatment for CORS.
//
// This method allows adding custom middleware functions to process requests before they
// reach the final handler. If a CORS middleware is detected, it is automatically applied.
//
// Parameters:
// - mw any: Middleware function to be added. It must be of type `func(http.Handler) http.Handler`.
//
// Example Usage:
//
// q := quick.New()
//
// q.Use(maxbody.New(50000))
//
// q.Post("/v1/user/maxbody/any", func(c *quick.Ctx) error {
// c.Set("Content-Type", "application/json")//
// return c.Status(200).Send(c.Body())
// })
func (q *Quick) Use(mw any) {
switch mwc := mw.(type) {
case func(http.Handler) http.Handler:
// Detect if the middleware is related to CORS and apply it separately
if isCorsMiddleware(mwc) {
q.Cors = true
q.CorsSet = mwc
return
}
case func(HandleFunc) HandleFunc:
q.mws2 = append(q.mws2, mwc)
}
// Append middleware to the list of registered middlewares
q.mws2 = append(q.mws2, mw)
}
// isCorsMiddleware checks whether the provided middleware function is a CORS handler.
//
// This function detects if a middleware is handling CORS by sending an
// HTTP OPTIONS request and checking if it sets the `Access-Control-Allow-Origin` header.
//
// Parameters:
// - mw func(http.Handler) http.Handler: The middleware function to be tested.
//
// Returns:
// - bool: `true` if the middleware is identified as CORS, `false` otherwise.
//
// Example Usage:
// This function is automatically executed when a middleware is added to detect if it's a CORS handler.
func isCorsMiddleware(mw func(http.Handler) http.Handler) bool {
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
testRequest := httptest.NewRequest("OPTIONS", "/", nil)
testResponse := httptest.NewRecorder()
mw(testHandler).ServeHTTP(testResponse, testRequest)
// If the middleware sets Access-Control-Allow-Origin, it's CORS
return testResponse.Header().Get("Access-Control-Allow-Origin") != ""
}
// clearRegex processes a route pattern, removing dynamic path parameters
// and replacing them with a simplified placeholder.
//
// This function is used internally to standardize dynamic routes in
// ServeMux, converting patterns like `/v1/user/{id:[0-9]+}` into
// `/v1/user/_id_`, making them easier to process.
//
// Parameters:
// - route string: The route pattern containing dynamic parameters.
//
// Returns:
// - string: A cleaned-up version of the route with placeholders instead of regex patterns.
//
// Example Usage:
// This function is automatically triggered internally to normalize route patterns.
func clearRegex(route string) string {
// Here you transform "/v1/user/{id:[0-9]+}"
// into something simple, like "/v1/user/_id_"
// You can get more sophisticated if you want
var re = regexp.MustCompile(`\{[^/]+\}`)
return re.ReplaceAllStringFunc(route, func(s string) string {
// s is "{id:[0-9]+}"
// Let's just replace it with "_id_"
// or any string that doesn't contain ":" or "{ }"
return "_" + strings.Trim(s, "{}") + "_"
//return "_" + strings.ReplaceAll(strings.ReplaceAll(strings.Trim(s, "{}"), ":", "_"), "[", "_") + "_"
})
}
// registerRoute is a helper function that centralizes the logic for registering routes.
//
// This function processes and registers an HTTP route, ensuring no duplicate routes
// are added. It extracts route parameters, formats the route, and associates the
// appropriate handler function.
//
// Parameters:
// - method string: The HTTP method (e.g., "GET", "POST").
// - pattern string: The route pattern, which may include dynamic parameters.
// - handlerFunc HandleFunc: The function that will handle the route.
//
// Example Usage:
// This function is automatically triggered internally when a new route is added.
func (q *Quick) registerRoute(method, pattern string, handlerFunc HandleFunc) {
path, params, patternExist := extractParamsPattern(pattern)
formattedPath := concat.String(strings.ToLower(method), "#", clearRegex(pattern))
for _, route := range q.routes {
if route.Method == method && route.Path == path {
fmt.Printf("Warning: Route '%s %s' is already registered, ignoring duplicate registration.\n", method, path)
return // Ignore duplication instead of generating panic
}
}
route := Route{
Pattern: patternExist,
Path: path,
Params: params,
handler: extractHandler(q, method, path, params, handlerFunc),
Method: method,
}
q.appendRoute(&route)
q.mux.HandleFunc(formattedPath, route.handler)
}
// handleOptions processes HTTP OPTIONS requests for CORS preflight checks.
// This function is automatically called before routing when an OPTIONS request is received.
// It ensures that the appropriate CORS headers are included in the response.
//
// If CORS middleware is enabled, it applies the middleware before setting default headers.
//
// Headers added by this function:
// - Access-Control-Allow-Origin: Allows cross-origin requests (set dynamically).
// - Access-Control-Allow-Methods: Specifies allowed HTTP methods (GET, POST, PUT, DELETE, OPTIONS).
// - Access-Control-Allow-Headers: Defines which headers are allowed in the request.
//
// If no Origin header is provided in the request, a 204 No Content response is returned.
//
// Parameters:
// - w: http.ResponseWriter – The response writer to send headers and status.
// - r: *http.Request – The incoming HTTP request.
//
// Response:
// - 204 No Content (if the request is valid and processed successfully).
//
// Example Usage:
// This function is automatically triggered in `ServeHTTP()` when an OPTIONS request is received.
func (q *Quick) handleOptions(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
w.WriteHeader(StatusNoContent)
return
}
// Apply CORS middleware before setting headers
if q.Cors && q.CorsSet != nil {
q.CorsSet(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})).ServeHTTP(w, r)
}
// Set default CORS headers
w.Header().Set("Allow", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Origin", "*") // Ajustável pelo middleware
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.WriteHeader(http.StatusNoContent) // Returns 204 No Content
}
// Get registers an HTTP route with the GET method on the Quick server.
//
// This function associates a GET request with a specific route pattern and handler function.
// It ensures that the request is properly processed when received.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users/:id").
// - handlerFunc HandleFunc: The function that will handle the GET request.
//
// Example Usage:
//
// // This function is automatically triggered when defining a GET route in Quick.
func (q *Quick) Get(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodGet, pattern, handlerFunc)
}
// Post registers an HTTP route with the POST method on the Quick server.
//
// This function associates a POST request with a specific route pattern and handler function.
// It is typically used for handling form submissions, JSON payloads, or data creation.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users").
// - handlerFunc HandleFunc: The function that will handle the POST request.
//
// Example Usage:
//
// // This function is automatically triggered when defining a POST route in Quick.
func (q *Quick) Post(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodPost, pattern, handlerFunc)
}
// Put registers an HTTP route with the PUT method on the Quick server.
//
// This function associates a PUT request with a specific route pattern and handler function.
// It is typically used for updating existing resources.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users/:id").
// - handlerFunc HandleFunc: The function that will handle the PUT request.
//
// Example Usage:
//
// // This function is automatically triggered when defining a PUT route in Quick.
func (q *Quick) Put(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodPut, pattern, handlerFunc)
}
// Delete registers an HTTP route with the DELETE method on the Quick server.
//
// This function associates a DELETE request with a specific route pattern and handler function.
// It is typically used for deleting existing resources.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users/:id").
// - handlerFunc HandleFunc: The function that will handle the DELETE request.
//
// Example Usage:
//
// // This function is automatically triggered when defining a DELETE route in Quick.
func (q *Quick) Delete(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodDelete, pattern, handlerFunc)
}
// Patch registers an HTTP route with the PATCH method on the Quick server.
//
// This function associates a PATCH request with a specific route pattern and handler function.
// It is typically used for applying partial updates to an existing resource.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users/:id").
// - handlerFunc HandleFunc: The function that will handle the PATCH request.
//
// Example Usage:
//
// // This function is automatically triggered when defining a PATCH route in Quick.
func (q *Quick) Patch(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodPatch, pattern, handlerFunc)
}
// Options registers an HTTP route with the OPTIONS method on the Quick server.
//
// This function associates an OPTIONS request with a specific route pattern and handler function.
// OPTIONS requests are typically used to determine the allowed HTTP methods for a resource.
//
// Parameters:
// - pattern string: The route pattern (e.g., "/users").
// - handlerFunc HandleFunc: The function that will handle the OPTIONS request.
//
// Example Usage:
//
// // This function is automatically triggered when defining an OPTIONS route in Quick.
func (q *Quick) Options(pattern string, handlerFunc HandleFunc) {
q.registerRoute(MethodOptions, pattern, handlerFunc)
}
// extractHandler selects the appropriate handler function for different HTTP methods.
//
// This function is responsible for determining which internal request processing function
// should handle a given HTTP method. It maps the method to the corresponding request parser.
//
// Parameters:
// - q *Quick: The Quick instance managing the route and request context.
// - method string: The HTTP method (e.g., "GET", "POST").
// - path string: The route path associated with the request.
// - params string: Route parameters extracted from the request URL.
// - handlerFunc HandleFunc: The function that will handle the request.
//
// Returns:
// - http.HandlerFunc: The appropriate handler function based on the HTTP method.
//
// Example Usage:
//
// // This function is automatically executed internally when processing an HTTP request.
func extractHandler(q *Quick, method, path, params string, handlerFunc HandleFunc) http.HandlerFunc {
switch method {
case MethodGet:
return extractParamsGet(q, path, params, handlerFunc)
case MethodPost:
return extractParamsPost(q, handlerFunc)
case MethodPut:
return extractParamsPut(q, handlerFunc)
case MethodDelete:
return extractParamsDelete(q, handlerFunc)
case MethodPatch:
return extractParamsPatch(q, handlerFunc) // same as PUT
case MethodOptions:
return extractParamsOptions(q, method, path, handlerFunc)
}
return nil
}
// extractParamsPatch processes an HTTP PATCH request by reusing the logic of the PUT method.
//
// The PATCH method is typically used for partial updates, while PUT replaces an entire resource.
// However, both methods often handle request parameters and body parsing in the same way,
// so this function delegates the processing to `extractParamsPut`.
//
// Parameters:
// - q *Quick: The Quick instance managing the request context.
// - handlerFunc HandleFunc: The function that will handle the PATCH request.
//
// Returns:
// - http.HandlerFunc: A handler function that processes PATCH requests.
//
// Example Usage:
//
// // This function is automatically executed internally when a PATCH request is received.
func extractParamsPatch(q *Quick, handlerFunc HandleFunc) http.HandlerFunc {
return extractParamsPut(q, handlerFunc)
}
// extractParamsOptions processes an HTTP OPTIONS request, setting appropriate
// headers to handle CORS preflight requests. It reuses a pooled Ctx instance
// for optimized memory usage and performance.
//
// If a handlerFunc is provided, it executes that handler with the pooled context.
// If no handlerFunc is given, it responds with HTTP 204 No Content.
//
// Parameters:
// - q: The Quick instance providing configurations and routing context.
// - method: The HTTP method being handled (typically "OPTIONS").
// - path: The route path being handled.
// - handlerFunc: An optional handler to execute for the OPTIONS request.
//
// Returns:
// - http.HandlerFunc: A handler function optimized for handling OPTIONS requests.
func extractParamsOptions(q *Quick, method, path string, handlerFunc HandleFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Acquire a pooled context
ctx := acquireCtx()
defer releaseCtx(ctx) // Ensure context is returned to the pool after handling
// Populate the pooled context
ctx.Response = w
ctx.Request = r
ctx.MoreRequests = q.config.MoreRequests
ctx.App = q
if q.Cors && q.CorsSet != nil {
wrappedHandler := q.CorsSet(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Middleware CORS apply success
}))
wrappedHandler.ServeHTTP(w, r)
}
if ctx.Response.Header().Get("Access-Control-Allow-Origin") == "" {
allowMethods := []string{MethodGet, MethodPost, MethodPut, MethodDelete, MethodPatch, MethodOptions}
ctx.Set("Allow", strings.Join(allowMethods, ", "))
ctx.Set("Access-Control-Allow-Origin", "*")
ctx.Set("Access-Control-Allow-Methods", strings.Join(allowMethods, ", "))
ctx.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
}
// Execute handler function if provided
if handlerFunc != nil {
if err := handlerFunc(ctx); err != nil {
http.Error(w, err.Error(), StatusInternalServerError)
}
} else {
w.WriteHeader(StatusNoContent) // 204 No Content if no handlerFunc
}
}
}
// extractHeaders extracts all headers from an HTTP request and returns them as a map.
//
// This function iterates over all headers in the request and organizes them into a
// map structure, where each header key is mapped to its corresponding values.
//
// Parameters:
// - req http.Request: The HTTP request from which headers will be extracted.
//
// Returns:
// - map[string][]string: A map containing all request headers.
//
// Example Usage:
//
// // This function is automatically executed internally when extracting headers from a request.
func extractHeaders(req http.Request) map[string][]string {
headersMap := make(map[string][]string)
for key, values := range req.Header {
headersMap[key] = values
}
return headersMap
}
// extractParamsBind decodes request bodies for JSON/XML payloads using a pooled buffer
// to minimize memory allocations and garbage collection overhead.
//
// This function checks the request's `Content-Type` and processes JSON or XML payloads accordingly.
// It ensures efficient memory usage by leveraging buffer pools for reading request bodies.
//
// Parameters:
// - c *Ctx: The Quick context containing request information.
// - v interface{}: The target structure where the decoded JSON/XML data will be stored.
//
// Returns:
// - error: Returns any decoding errors encountered or an error for unsupported content types.
//
// Example Usage:
//
// // This function is automatically executed internally when binding request data to a struct.
func extractParamsBind(c *Ctx, v interface{}) error {
contentType := strings.ToLower(c.Request.Header.Get("Content-Type"))
// Check supported Content-Type
if !strings.HasPrefix(contentType, ContentTypeAppJSON) &&
!strings.HasPrefix(contentType, ContentTypeAppXML) &&
!strings.HasPrefix(contentType, ContentTypeTextXML) {
return fmt.Errorf("unsupported content type: %s", contentType)
}
switch {
case strings.HasPrefix(contentType, ContentTypeAppJSON):
// Acquire pooled buffer
buf := acquireJSONBuffer()
defer releaseJSONBuffer(buf)
// Read body content into buffer
if _, err := buf.ReadFrom(c.Request.Body); err != nil {
return err
}
// Reset the Request.Body after reading, enabling re-reads if needed
c.Request.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
return json.Unmarshal(buf.Bytes(), v)
case strings.HasPrefix(contentType, ContentTypeAppXML), strings.HasPrefix(contentType, ContentTypeTextXML):
// Acquire pooled buffer
buf := acquireXMLBuffer()
defer releaseXMLBuffer(buf)
// Read body content into buffer
if _, err := buf.ReadFrom(c.Request.Body); err != nil {
return err
}
// Reset the Request.Body after reading, enabling re-reads if needed
c.Request.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
return xml.Unmarshal(buf.Bytes(), v)
default:
return fmt.Errorf("unsupported content type: %s", contentType)
}
}
// extractParamsPattern extracts the fixed path and dynamic parameters from a given route pattern.
//
// This function is responsible for identifying and separating static paths from dynamic parameters
// in a route pattern. It ensures proper extraction of URL path segments and dynamic query parameters.
//
// Parameters:
// - pattern string: The route pattern that may contain dynamic parameters.
//
// Returns:
// - path string: The fixed portion of the route without dynamic parameters.
// - params string: The extracted dynamic parameters (if any).
// - patternExist string: The original pattern before extraction.
//
// Example Usage:
//
// // This function is automatically executed internally when registering a dynamic route.
// path, params, patternExist := extractParamsPattern("/users/:id")
func extractParamsPattern(pattern string) (path, params, partternExist string) {
path = pattern
index := strings.Index(pattern, ":")
if index > 0 {
path = pattern[:index]
path = strings.TrimSuffix(path, "/")
if index == 1 {
path = "/"
}
params = strings.TrimPrefix(pattern, path)
partternExist = pattern
}
return
}
// extractParamsGet processes an HTTP GET request for a dynamic route,
// extracting query parameters, headers, and handling the request using
// the provided handler function.
//
// This function ensures efficient processing by leveraging a pooled
// Ctx instance, which minimizes memory allocations and reduces garbage
// collection overhead.
//
// The request context (`myContextKey`) is retrieved to extract dynamic
// parameters mapped to the route.
//
// Parameters:
// - q: The Quick instance that provides configurations and routing context.
// - pathTmp: The template path used for dynamic route matching.
// - paramsPath: The actual path used to extract route parameters.
// - handlerFunc: The function that processes the HTTP request.
//
// Returns:
// - http.HandlerFunc: A function that processes the request efficiently.
func extractParamsGet(q *Quick, pathTmp, paramsPath string, handlerFunc HandleFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// Acquire a context from the pool
ctx := acquireCtx()
defer releaseCtx(ctx)
// Retrieve the custom context from the request (myContextKey)
v := req.Context().Value(myContextKey)
if v == nil {
NotFound(w, req)
return
}
cval := v.(ctxServeHttp)
// Fill the pooled context with request-specific data
ctx.Response = w
ctx.Request = req
ctx.Params = cval.ParamsMap
ctx.App = q
// Initialize Query and Headers maps properly
ctx.Query = make(map[string]string)
for key, val := range req.URL.Query() {
ctx.Query[key] = val[0]
}
ctx.Headers = extractHeaders(*req)
ctx.MoreRequests = q.config.MoreRequests
// Execute the handler function using the pooled context
execHandleFunc(ctx, handlerFunc)
}
}
// extractParamsPost processes an HTTP POST request, extracting the request body
// and headers and handling the request using the provided handler function.
//
// This function ensures that the request body is within the allowed size limit,
// extracts headers, and reuses a pooled Ctx instance to optimize memory usage.
//
// Parameters:
// - q: The Quick instance that provides configurations and routing context.
// - handlerFunc: The function that processes the HTTP request.
//
// Returns:
// - http.HandlerFunc: A handler function that processes the request efficiently.
func extractParamsPost(q *Quick, handlerFunc HandleFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// Validate body size before processing
// req.Body = http.MaxBytesReader(w, req.Body, q.config.MaxBodySize)
if req.ContentLength > q.config.MaxBodySize {
http.Error(w, "Request body too large", StatusRequestEntityTooLarge)
return
}
// Acquire a pooled context for request processing
ctx := acquireCtx()
defer releaseCtx(ctx) // Ensure the context is returned to the pool after execution
// Retrieve the custom context from the request
v := req.Context().Value(myContextKey)
if v == nil {
NotFound(w, req) // Return 404 if no context value is found
return
}
// Extract headers into the pooled Ctx
ctx.Headers = extractHeaders(*req)
// Read the request body while minimizing allocations
bodyBytes, bodyReader := extractBodyBytes(req.Body)
// Populate the Ctx with relevant data
ctx.Response = w
ctx.Request = req
ctx.bodyByte = bodyBytes
ctx.MoreRequests = q.config.MoreRequests
// Reset `Request.Body` with the new bodyReader to allow re-reading
ctx.Request.Body = bodyReader
ctx.App = q
// Execute the handler function using the pooled context
execHandleFunc(ctx, handlerFunc)
}
}
// extractParamsPut processes an HTTP PUT request, extracting the request body,
// headers, and route parameters while efficiently reusing a pooled Ctx instance.
//
// This function ensures that the request body does not exceed the configured
// size limit, extracts headers, and minimizes memory allocations by leveraging
// a preallocated Ctx from the sync.Pool.
//
// Parameters: