@@ -298,13 +298,50 @@ impl Router {
298298 self . plugins . iter ( ) . map ( |plugin| plugin. as_ref ( ) ) . collect ( )
299299 }
300300
301+ /// Merges another `Router` into the current `Router`.
302+ ///
303+ /// This method combines the routes and middlewares of the provided `Router`
304+ /// into the current `Router`. Routes from the other `Router` are added to
305+ /// the current one, and its middlewares are prepended to the route-level
306+ /// middlewares of the merged routes.
307+ ///
308+ /// # Arguments
309+ ///
310+ /// * `other` - The `Router` instance to merge into the current `Router`.
311+ ///
312+ /// # Behavior
313+ ///
314+ /// - Routes from the `other` router are added to the current router.
315+ /// - Middlewares defined at the router level in the `other` router are
316+ /// prepended to the route-level middlewares of the merged routes.
317+ ///
318+ /// # Example
319+ ///
320+ /// ```rust
321+ /// use tako::router::Router;
322+ /// use http::Method;
323+ ///
324+ /// let mut router1 = Router::new();
325+ /// router1.route(Method::GET, "/example1", |req| async move {
326+ /// Ok(req)
327+ /// });
328+ ///
329+ /// let mut router2 = Router::new();
330+ /// router2.route(Method::POST, "/example2", |req| async move {
331+ /// Ok(req)
332+ /// });
333+ ///
334+ /// router1.merge(router2);
335+ /// ```
301336 pub fn merge ( & mut self , other : Router ) {
302- other. routes . into_iter ( ) . for_each ( |route| { } ) ;
303- other
304- . middlewares
305- . read ( )
306- . unwrap ( )
307- . iter ( )
308- . for_each ( |middleware| { } ) ;
337+ other. routes . iter_mut ( ) . for_each ( |mut entry| {
338+ let ( key, route) = entry. pair_mut ( ) ;
339+ // add router level middlewares at the beginning of the middlewares on route level
340+ for mw in other. middlewares . read ( ) . unwrap ( ) . iter ( ) . rev ( ) {
341+ route. middlewares . write ( ) . unwrap ( ) . push_front ( mw. clone ( ) ) ;
342+ }
343+
344+ self . routes . insert ( key. to_owned ( ) , route. to_owned ( ) ) ;
345+ } ) ;
309346 }
310347}
0 commit comments