RegisterRoute adds an HTTP route to the server with the specified middleware chain. Routes are matched by both method and path, unless the method is CATCHALL (empty string) which matches all methods. Middleware is applied in the order provided, with each middleware wrapping the next. The innermost
(middlewares []Middleware, route Route)
| 279 | // zen.NewRoute(zen.CATCHALL, "/{path...}", proxyHandler), |
| 280 | // ) |
| 281 | func (s *Server) RegisterRoute(middlewares []Middleware, route Route) { |
| 282 | path := route.Path() |
| 283 | method := route.Method() |
| 284 | logger.Info("registering", "method", method, "path", path) |
| 285 | |
| 286 | // Determine the pattern based on whether this is a catch-all route |
| 287 | // Empty method means match all HTTP methods |
| 288 | pattern := path |
| 289 | if method != "" { |
| 290 | pattern = method + " " + path |
| 291 | } |
| 292 | |
| 293 | s.mux.HandleFunc( |
| 294 | pattern, |
| 295 | func(w http.ResponseWriter, r *http.Request) { |
| 296 | sess, ok := s.getSession().(*Session) |
| 297 | if !ok { |
| 298 | panic("Unable to cast session") |
| 299 | } |
| 300 | |
| 301 | defer func() { |
| 302 | sess.reset() |
| 303 | s.returnSession(sess) |
| 304 | }() |
| 305 | |
| 306 | handleFn := route.Handle |
| 307 | |
| 308 | err := sess.Init(w, r, s.config.MaxRequestBodySize) |
| 309 | if err != nil { |
| 310 | logger.Error("failed to init session", "error", err) |
| 311 | handleFn = func(_ context.Context, _ *Session) error { |
| 312 | return err // Return the session init error |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // Reverses the middlewares to run in the desired order. |
| 317 | // If middlewares are [A, B, C], this writes [C, B, A] to s.middlewares. |
| 318 | for i := len(middlewares) - 1; i >= 0; i-- { |
| 319 | handleFn = middlewares[i](handleFn) |
| 320 | } |
| 321 | |
| 322 | err = handleFn(WithSession(r.Context(), sess), sess) |
| 323 | |
| 324 | if err != nil { |
| 325 | panic(err) |
| 326 | } |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | // Shutdown gracefully stops the HTTP server, allowing in-flight requests |
| 331 | // to complete before returning or the context is canceled. |