11use  std:: collections:: HashMap ; 
22
3+ use  crate :: core:: res_body:: ResBody ; 
34use  crate :: { Request ,  Response ,  Result ,  SilentError } ; 
45use  async_trait:: async_trait; 
56use  http:: { Method ,  StatusCode } ; 
@@ -17,17 +18,29 @@ pub trait Handler: Send + Sync + 'static {
1718#[ async_trait]  
1819impl  Handler  for  HashMap < Method ,  Arc < dyn  Handler > >  { 
1920    async  fn  call ( & self ,  req :  Request )  -> Result < Response >  { 
20-         match  self . clone ( ) . get ( req. method ( ) )  { 
21-             None  => Err ( SilentError :: business_error ( 
22-                 StatusCode :: METHOD_NOT_ALLOWED , 
23-                 "method not allowed" . to_string ( ) , 
24-             ) ) , 
25-             Some ( handler)  => { 
26-                 let  mut  pre_res = Response :: empty ( ) ; 
27-                 pre_res. configs  = req. configs ( ) ; 
28-                 pre_res. copy_from_response ( handler. call ( req) . await ?) ; 
29-                 Ok ( pre_res) 
30-             } 
21+         let  method = req. method ( ) . clone ( ) ; 
22+         // 直接命中匹配的方法 
23+         if  let  Some ( handler)  = self . clone ( ) . get ( & method)  { 
24+             let  mut  pre_res = Response :: empty ( ) ; 
25+             pre_res. configs  = req. configs ( ) ; 
26+             pre_res. copy_from_response ( handler. call ( req) . await ?) ; 
27+             return  Ok ( pre_res) ; 
3128        } 
29+ 
30+         // 特殊处理:HEAD 无显式处理器时回退到 GET,并清空响应体 
31+         if  method == http:: Method :: HEAD 
32+             && let  Some ( get_handler)  = self . clone ( ) . get ( & http:: Method :: GET ) 
33+         { 
34+             let  mut  pre_res = Response :: empty ( ) ; 
35+             pre_res. configs  = req. configs ( ) ; 
36+             pre_res. copy_from_response ( get_handler. call ( req) . await ?) ; 
37+             pre_res. set_body ( ResBody :: None ) ; 
38+             return  Ok ( pre_res) ; 
39+         } 
40+ 
41+         Err ( SilentError :: business_error ( 
42+             StatusCode :: METHOD_NOT_ALLOWED , 
43+             "method not allowed" . to_string ( ) , 
44+         ) ) 
3245    } 
3346} 
0 commit comments