ntex/web/util.rs
1//! Essentials helper functions and types for application registration.
2use std::fmt;
3
4use ntex_router::IntoPattern;
5
6use crate::error::IntoFailure;
7use crate::http::error::{BlockingError, ResponseError};
8use crate::http::header::ContentEncoding;
9use crate::http::{Method, Request, Response};
10use crate::server::{NoConfig, ServerAppConfig};
11use crate::service::{IntoServiceFactory, ServiceFactory};
12
13use super::extract::FromRequest;
14use super::handler::{Handler, HandlerSt};
15use super::resource::Resource;
16use super::route::Route;
17use super::scope::Scope;
18use super::server::HttpServer;
19use super::service::WebServiceAdapter;
20use super::{HttpResponse, HttpResponseBuilder, State, WebResponseError};
21
22/// Create resource for a specific path.
23///
24/// Resources may have variable path segments. For example, a
25/// resource with the path `/a/{name}/c` would match all incoming
26/// requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`.
27///
28/// A variable segment is specified in the form `{identifier}`,
29/// where the identifier can be used later in a request handler to
30/// access the matched value for that segment. This is done by
31/// looking up the identifier in the `Params` object returned by
32/// `HttpRequest.match_info()` method.
33///
34/// By default, each segment matches the regular expression `[^{}/]+`.
35///
36/// You can also specify a custom regex in the form `{identifier:regex}`.
37///
38/// For instance, to route `GET`-requests on any route matching
39/// `/users/{userid}/{friend}` and store `userid` and `friend` in
40/// the exposed `Params` object:
41///
42/// ```rust,no_run
43/// use ntex::web;
44///
45/// #[ntex::main]
46/// async fn main() -> std::io::Result<()> {
47/// web::server(async |_| {
48/// web::App::new().service(
49/// web::resource("/users/{userid}/{friend}")
50/// .route(web::get().to(async || { web::HttpResponse::Ok() }))
51/// .route(web::head().to(async || { web::HttpResponse::MethodNotAllowed() }))
52/// )
53/// })
54/// .bind("127.0.0.1:59090", ntex::SharedCfg::default())?
55/// .run()
56/// .await
57/// }
58/// ```
59pub fn resource<St: State, In: 'static, T: IntoPattern>(path: T) -> Resource<St, In> {
60 Resource::new(path)
61}
62
63/// Configure scope for common root path.
64///
65/// Scopes collect multiple paths under a common path prefix.
66/// Scope path can contain variable path segments as resources.
67///
68/// ```rust,no_run
69/// use ntex::web;
70///
71/// #[ntex::main]
72/// async fn main() -> std::io::Result<()> {
73/// web::server(async |_| {
74/// web::App::new().service(
75/// web::scope("/{project_id}")
76/// .service(web::resource("/path1").to(async || { web::HttpResponse::Ok() }))
77/// .service(web::resource("/path2").to(async || { web::HttpResponse::Ok() }))
78/// .service(web::resource("/path3").to(async || { web::HttpResponse::MethodNotAllowed() }))
79/// )
80/// })
81/// .bind("127.0.0.1:59090", ntex::SharedCfg::default())?
82/// .run()
83/// .await
84/// }
85/// ```
86///
87/// In the above example, three routes get added:
88/// * `/{project_id}/path1`
89/// * `/{project_id}/path2`
90/// * `/{project_id}/path3`
91///
92pub fn scope<St: State, In: 'static, T: IntoPattern>(path: T) -> Scope<St, In> {
93 Scope::new(path)
94}
95
96/// Create *route* without configuration.
97pub fn route<St: State, U: 'static>() -> Route<St, U> {
98 Route::new()
99}
100
101/// Create *route* with `GET` method guard.
102///
103/// ```rust
104/// use ntex::web;
105///
106/// let app = web::App::default().service(
107/// web::resource("/{project_id}")
108/// .route(web::get().to(async || { web::HttpResponse::Ok() }))
109/// );
110/// ```
111///
112/// In the above example, one `GET` route gets added:
113/// * `/{project_id}`
114///
115pub fn get<St: State, U: 'static>() -> Route<St, U> {
116 method(Method::GET)
117}
118
119/// Create *route* with `POST` method guard.
120///
121/// ```rust
122/// use ntex::web;
123///
124/// let app = web::App::default().service(
125/// web::resource("/{project_id}")
126/// .route(web::post().to(async || { web::HttpResponse::Ok() }))
127/// );
128/// ```
129///
130/// In the above example, one `POST` route gets added:
131/// * `/{project_id}`
132///
133pub fn post<St: State, U: 'static>() -> Route<St, U> {
134 method(Method::POST)
135}
136
137/// Create *route* with `PUT` method guard.
138///
139/// ```rust
140/// use ntex::web;
141///
142/// let app = web::App::default().service(
143/// web::resource("/{project_id}")
144/// .route(web::put().to(async || { web::HttpResponse::Ok() }))
145/// );
146/// ```
147///
148/// In the above example, one `PUT` route gets added:
149/// * `/{project_id}`
150///
151pub fn put<St: State, U: 'static>() -> Route<St, U> {
152 method(Method::PUT)
153}
154
155/// Create *route* with `PATCH` method guard.
156///
157/// ```rust
158/// use ntex::web;
159///
160/// let app = web::App::default().service(
161/// web::resource("/{project_id}")
162/// .route(web::patch().to(async || { web::HttpResponse::Ok() }))
163/// );
164/// ```
165///
166/// In the above example, one `PATCH` route gets added:
167/// * `/{project_id}`
168///
169pub fn patch<St: State, U: 'static>() -> Route<St, U> {
170 method(Method::PATCH)
171}
172
173/// Create *route* with `DELETE` method guard.
174///
175/// ```rust
176/// use ntex::web;
177///
178/// let app = web::App::default().service(
179/// web::resource("/{project_id}")
180/// .route(web::delete().to(async || { web::HttpResponse::Ok() }))
181/// );
182/// ```
183///
184/// In the above example, one `DELETE` route gets added:
185/// * `/{project_id}`
186///
187pub fn delete<St: State, U: 'static>() -> Route<St, U> {
188 method(Method::DELETE)
189}
190
191/// Create *route* with `HEAD` method guard.
192///
193/// ```rust
194/// use ntex::web;
195///
196/// let app = web::App::default().service(
197/// web::resource("/{project_id}")
198/// .route(web::head().to(async || { web::HttpResponse::Ok() }))
199/// );
200/// ```
201///
202/// In the above example, one `HEAD` route gets added:
203/// * `/{project_id}`
204///
205pub fn head<St: State, U: 'static>() -> Route<St, U> {
206 method(Method::HEAD)
207}
208
209/// Create *route* with `QUERY` method guard.
210///
211/// ```rust
212/// use ntex::web;
213///
214/// let app = web::App::default().service(
215/// web::resource("/{project_id}")
216/// .route(web::query().to(async || { web::HttpResponse::Ok() }))
217/// );
218/// ```
219///
220/// In the above example, one `QUERY` route gets added:
221/// * `/{project_id}`
222///
223pub fn query<St: State, U: 'static>() -> Route<St, U> {
224 method(Method::QUERY)
225}
226
227/// Create *route* and add method guard.
228///
229/// ```rust
230/// use ntex::{http, web};
231///
232/// let app = web::App::default().service(
233/// web::resource("/{project_id}")
234/// .route(web::method(http::Method::GET).to(async || { web::HttpResponse::Ok() }))
235/// );
236/// ```
237///
238/// In the above example, one `GET` route gets added:
239/// * `/{project_id}`
240///
241pub fn method<St: State, U: 'static>(method: Method) -> Route<St, U> {
242 Route::default().method(method)
243}
244
245/// Create an unguarded route with a handler.
246///
247/// The handler receives values produced by request extractors and returns a
248/// type implementing [`Responder`](super::Responder). If extraction fails, the
249/// error is converted into a response and the handler is not called.
250///
251/// The returned route has no method or custom guards, so it matches every
252/// request considered by its resource. Add guards before the handler with
253/// helpers such as [`get()`] or with [`Route::guard()`].
254///
255/// ```rust
256/// use ntex::web;
257///
258/// async fn show_user(id: web::types::Path<u32>) -> String {
259/// format!("User {}", id.into_inner())
260/// }
261///
262/// web::App::default().service(
263/// web::resource("/users/{id}").route(web::to(show_user))
264/// );
265/// ```
266pub fn to<St, In, F, Args>(handler: F) -> Route<St, In>
267where
268 St: State,
269 In: 'static,
270 F: Handler<St, Args> + 'static,
271 Args: FromRequest<St> + 'static,
272 Args::Error: WebResponseError<St, St::Error>,
273{
274 Route::new().to(handler)
275}
276
277/// Create a new route with a state-aware handler.
278///
279/// The handler receives a shared reference to the application state, followed
280/// by the request state and any request extractors. Use [`to()`] when the
281/// handler only needs request extractors.
282///
283/// ```rust
284/// use std::convert::Infallible;
285/// use ntex::web::{self, WebRequest};
286///
287/// struct AppState {
288/// greeting: &'static str,
289/// }
290///
291/// impl web::State for AppState {
292/// type Error = web::DefaultError;
293/// }
294///
295/// async fn index(
296/// state: &AppState,
297/// request_state: usize,
298/// name: web::types::Path<String>,
299/// ) -> String {
300/// let _ = request_state;
301/// format!("{}, {}!", state.greeting, name.into_inner())
302/// }
303///
304/// web::App::<AppState>::new().service(
305/// web::resource("/{name}")
306/// .filter(async |req: WebRequest<()>| {
307/// Ok::<_, Infallible>(req.map_state(|_| 10usize))
308/// })
309/// .route(web::to_with_state(index))
310/// );
311/// ```
312pub fn to_with_state<St, In, F, Args>(handler: F) -> Route<St, In>
313where
314 St: State,
315 In: 'static,
316 F: HandlerSt<St, In, Args> + 'static,
317 Args: FromRequest<St> + 'static,
318 Args::Error: WebResponseError<St, St::Error>,
319{
320 Route::new().to_with_state(handler)
321}
322
323/// Create service adapter for a specific path.
324///
325/// ```rust
326/// use std::convert::Infallible;
327/// use ntex::web::{self, guard, App, HttpResponse, WebError};
328///
329/// async fn my_service(req: web::WebRequest<()>) -> Result<web::WebResponse, Infallible> {
330/// Ok(req.into_response(HttpResponse::Ok().build()))
331/// }
332///
333/// let app = App::default().service(
334/// web::service("/users/*")
335/// .guard(guard::Header("content-type", "text/plain"))
336/// .build(my_service)
337/// );
338/// ```
339pub fn service<T: IntoPattern>(path: T) -> WebServiceAdapter {
340 WebServiceAdapter::new(path)
341}
342
343/// Execute blocking function on a thread pool, returns future that resolves
344/// to result of the function execution.
345pub async fn block<F, I, E>(f: F) -> Result<I, BlockingError<E>>
346where
347 F: FnOnce() -> Result<I, E> + Send + Sync + 'static,
348 I: Send + 'static,
349 E: Send + fmt::Debug + 'static,
350{
351 match crate::rt::spawn_blocking(f).await {
352 Ok(res) => res.map_err(BlockingError::Error),
353 Err(_) => Err(BlockingError::Canceled),
354 }
355}
356
357/// Create new http server with application factory.
358///
359/// ```rust,no_run
360/// use ntex::{web, SharedCfg};
361///
362/// #[ntex::main]
363/// async fn main() -> std::io::Result<()> {
364/// web::server(async |_| {
365/// web::App::new()
366/// .service(web::resource("/").to(async || { web::HttpResponse::Ok() }))
367/// })
368/// .bind("127.0.0.1:59090", SharedCfg::default())?
369/// .run()
370/// .await
371/// }
372/// ```
373pub fn server<F, I, Sf>(factory: F) -> HttpServer<NoConfig, F, I, Sf>
374where
375 F: AsyncFn(&()) -> I + Send + Clone + 'static,
376 I: IntoServiceFactory<Sf, (), Request>,
377 Sf: ServiceFactory<(), Request> + 'static,
378 Sf::Res: Into<Response>,
379 Sf::Error: ResponseError,
380 Sf::InitError: IntoFailure,
381{
382 HttpServer::new(factory)
383}
384
385/// Create new http server with application factory and configuration.
386///
387/// ```rust,no_run
388/// use std::io;
389/// use ntex::{web, SharedCfg};
390///
391/// #[derive(Clone)]
392/// struct AppState;
393///
394/// impl web::State for AppState {
395/// type Error = web::DefaultError;
396/// }
397///
398/// struct AppStateBuilder;
399///
400/// impl ntex::server::ServerAppConfig for AppStateBuilder {
401/// type State = AppState;
402///
403/// async fn create(&self) -> io::Result<Self::State> {
404/// Ok(AppState)
405/// }
406/// }
407///
408/// #[ntex::main]
409/// async fn main() -> io::Result<()> {
410/// web::server_with_config(AppStateBuilder, async |_| {
411/// web::App::new()
412/// .service(web::resource("/").to(async || { web::HttpResponse::Ok() }))
413/// })
414/// .bind("127.0.0.1:59090", SharedCfg::default())?
415/// .run()
416/// .await
417/// }
418/// ```
419pub fn server_with_config<Cfg, F, I, Sf>(cfg: Cfg, factory: F) -> HttpServer<Cfg, F, I, Sf>
420where
421 Cfg: ServerAppConfig,
422 F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
423 I: IntoServiceFactory<Sf, Cfg::State, Request>,
424 Sf: ServiceFactory<Cfg::State, Request> + 'static,
425 Sf::Res: Into<Response>,
426 Sf::Error: ResponseError,
427 Sf::InitError: IntoFailure,
428{
429 HttpServer::with_config(cfg, factory)
430}
431
432struct Enc(ContentEncoding);
433
434/// Helper trait that allows to set specific encoding for response.
435pub trait BodyEncoding {
436 /// Get content encoding
437 fn get_encoding(&self) -> Option<ContentEncoding>;
438
439 /// Set content encoding
440 fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self;
441}
442
443impl BodyEncoding for HttpResponseBuilder {
444 fn get_encoding(&self) -> Option<ContentEncoding> {
445 self.extensions().get::<Enc>().as_ref().map(|enc| enc.0)
446 }
447
448 fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
449 self.extensions_mut().insert(Enc(encoding));
450 self
451 }
452}
453
454impl<B> BodyEncoding for HttpResponse<B> {
455 fn get_encoding(&self) -> Option<ContentEncoding> {
456 self.extensions().get::<Enc>().as_ref().map(|enc| enc.0)
457 }
458
459 fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
460 self.extensions_mut().insert(Enc(encoding));
461 self
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 #[test]
470 fn body_encoding() {
471 let mut builder = HttpResponse::Ok();
472 assert_eq!(builder.get_encoding(), None);
473 builder.encoding(ContentEncoding::Gzip);
474 assert_eq!(builder.get_encoding(), Some(ContentEncoding::Gzip));
475
476 let mut res = builder.build();
477 assert_eq!(res.get_encoding(), Some(ContentEncoding::Gzip));
478 res.encoding(ContentEncoding::Identity);
479 assert_eq!(res.get_encoding(), Some(ContentEncoding::Identity));
480 }
481
482 #[crate::rt_test]
483 async fn block_canceled() {
484 let res = block(|| -> Result<(), ()> { panic!("blocking panic") }).await;
485 assert!(matches!(res, Err(BlockingError::Canceled)));
486
487 let res = block(|| Err::<(), _>("err")).await;
488 assert!(matches!(res, Err(BlockingError::Error("err"))));
489 }
490}