MCPcopy
hub / github.com/unkeyed/unkey / RegisterRoute

Method RegisterRoute

pkg/zen/server.go:281–328  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

279// zen.NewRoute(zen.CATCHALL, "/{path...}", proxyHandler),
280// )
281func (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.

Calls 9

getSessionMethod · 0.95
returnSessionMethod · 0.95
WithSessionFunction · 0.85
resetMethod · 0.80
ContextMethod · 0.80
PathMethod · 0.65
MethodMethod · 0.65
InitMethod · 0.65
ErrorMethod · 0.45