@@ -9,6 +9,7 @@ use crate::{
99 HttpRequest ,
1010 error:: Error ,
1111 http:: {
12+ Extensions ,
1213 endpoints:: args:: { FromPayload , FromRequestParts , FromRequestRef , Payload , Source } ,
1314 request_scope:: HttpRequestScope ,
1415 } ,
@@ -72,26 +73,30 @@ impl Clone for TokenGuard {
7273 }
7374}
7475
76+ impl From < & Extensions > for TokenGuard {
77+ #[ inline]
78+ fn from ( extensions : & Extensions ) -> Self {
79+ let token = extensions
80+ . get :: < HttpRequestScope > ( )
81+ . map ( |s| s. cancellation_token . clone ( ) )
82+ . unwrap_or_else ( TokioCancellationToken :: new) ;
83+ Self :: new ( token)
84+ }
85+ }
86+
7587/// Extracts `CancellationToken` from request parts
7688impl FromRequestParts for TokenGuard {
7789 #[ inline]
7890 fn from_parts ( parts : & Parts ) -> Result < Self , Error > {
79- parts
80- . extensions
81- . get :: < HttpRequestScope > ( )
82- . map ( |s| Self :: new ( s. cancellation_token . clone ( ) ) )
83- . ok_or_else ( || Error :: server_error ( "CancellationToken: missing" ) )
91+ Ok ( Self :: from ( & parts. extensions ) )
8492 }
8593}
8694
8795/// Extracts `CancellationToken` from request
8896impl FromRequestRef for TokenGuard {
8997 #[ inline]
9098 fn from_request ( req : & HttpRequest ) -> Result < Self , Error > {
91- req. extensions ( )
92- . get :: < HttpRequestScope > ( )
93- . map ( |s| Self :: new ( s. cancellation_token . clone ( ) ) )
94- . ok_or_else ( || Error :: server_error ( "CancellationToken: missing" ) )
99+ Ok ( Self :: from ( req. extensions ( ) ) )
95100 }
96101}
97102
@@ -145,12 +150,28 @@ mod tests {
145150 }
146151
147152 #[ test]
148- fn it_gets_err_from_parts_if_scope_missing ( ) {
153+ fn it_gets_new_token_from_parts_if_scope_missing ( ) {
149154 let req = Request :: get ( "/" ) . body ( ( ) ) . unwrap ( ) ;
150155 let ( parts, _) = req. into_parts ( ) ;
151- assert ! ( TokenGuard :: from_parts( & parts) . is_err ( ) ) ;
156+ assert ! ( TokenGuard :: from_parts( & parts) . is_ok ( ) ) ;
152157 }
153158
159+ #[ test]
160+ fn it_gets_from_extensions ( ) {
161+ let token = TokioCancellationToken :: new ( ) ;
162+ token. cancel ( ) ;
163+
164+ let req = Request :: get ( "/" )
165+ . extension ( make_scope_with_token ( token) )
166+ . body ( ( ) )
167+ . unwrap ( ) ;
168+
169+ let ( parts, _) = req. into_parts ( ) ;
170+ let token = TokenGuard :: from ( & parts. extensions ) ;
171+
172+ assert ! ( token. is_cancelled( ) ) ;
173+ }
174+
154175 #[ test]
155176 fn it_gets_from_request_parts ( ) {
156177 let token = TokioCancellationToken :: new ( ) ;
0 commit comments