@@ -96,13 +96,6 @@ func (a *Intake) AddEndpoints(e ...Endpoints) {
96
96
// - finalHandler: The handler function that will process the request
97
97
// - middleware: Optional route-specific middleware functions
98
98
func (a * Intake ) AddEndpoint (verb string , path string , finalHandler http.HandlerFunc , middleware ... MiddleWare ) {
99
- mws := append (a .GlobalMiddleware , middleware ... )
100
- for i := len (mws ) - 1 ; i >= 0 ; i -- {
101
- if mws [i ] != nil {
102
- finalHandler = mws [i ](finalHandler )
103
- }
104
- }
105
-
106
99
// Store the route in our registry
107
100
if methods , exists := a .registeredRoutes [path ]; exists {
108
101
a .registeredRoutes [path ] = append (methods , verb )
@@ -111,17 +104,36 @@ func (a *Intake) AddEndpoint(verb string, path string, finalHandler http.Handler
111
104
}
112
105
113
106
handlerKey := fmt .Sprintf ("%s %s" , verb , path )
114
- a .Mux .HandleFunc (handlerKey , func (w http.ResponseWriter , r * http.Request ) {
115
- // Apply panic recovery if a handler is provided
107
+
108
+ // Apply global middleware first
109
+ var handler http.HandlerFunc = func (w http.ResponseWriter , r * http.Request ) {
110
+ // Apply panic recovery here to capture panics in both global and route middleware
116
111
if a .PanicHandler != nil {
117
112
defer func () {
118
113
if err := recover (); err != nil {
119
114
a .PanicHandler (w , r , err )
120
115
}
121
116
}()
122
117
}
123
- finalHandler (w , r )
124
- })
118
+
119
+ // Apply route middleware and the final handler
120
+ routeHandler := finalHandler
121
+ for i := len (middleware ) - 1 ; i >= 0 ; i -- {
122
+ if middleware [i ] != nil {
123
+ routeHandler = middleware [i ](routeHandler )
124
+ }
125
+ }
126
+ routeHandler (w , r )
127
+ }
128
+
129
+ // Apply global middleware in reverse order
130
+ for i := len (a .GlobalMiddleware ) - 1 ; i >= 0 ; i -- {
131
+ if a .GlobalMiddleware [i ] != nil {
132
+ handler = a.GlobalMiddleware [i ](handler )
133
+ }
134
+ }
135
+
136
+ a .Mux .HandleFunc (handlerKey , handler )
125
137
}
126
138
127
139
// Run starts the HTTP server and handles graceful shutdown on SIGINT/SIGTERM.
@@ -190,4 +202,4 @@ func (a *Intake) AddOptionsEndpoints() {
190
202
// Register the OPTIONS handler for this path
191
203
a .AddEndpoint (http .MethodOptions , path , optionsHandler )
192
204
}
193
- }
205
+ }
0 commit comments