[][src]Struct actix_web::App

pub struct App<T, B> { /* fields omitted */ }

Application builder - structure that follows the builder pattern for building application instances.

Implementations

impl App<AppEntry, Body>[src]

pub fn new() -> Self[src]

Create application builder. Application can be configured with a builder-like pattern.

impl<T, B> App<T, B> where
    B: MessageBody,
    T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>, 
[src]

pub fn data<U: 'static>(self, data: U) -> Self[src]

Set application data. Application data could be accessed by using Data<T> extractor where T is data type.

Note: http server accepts an application factory rather than an application instance. Http server constructs an application instance for each thread, thus application data must be constructed multiple times. If you want to share data between different threads, a shared object should be used, e.g. Arc. Internally Data type uses Arc so data could be created outside of app factory and clones could be stored via App::app_data() method.

use std::cell::Cell;
use actix_web::{web, App, HttpResponse, Responder};

struct MyData {
    counter: Cell<usize>,
}

async fn index(data: web::Data<MyData>) -> impl Responder {
    data.counter.set(data.counter.get() + 1);
    HttpResponse::Ok()
}

let app = App::new()
    .data(MyData{ counter: Cell::new(0) })
    .service(
        web::resource("/index.html").route(
            web::get().to(index)));

pub fn data_factory<F, Out, D, E>(self, data: F) -> Self where
    F: Fn() -> Out + 'static,
    Out: Future<Output = Result<D, E>> + 'static,
    D: 'static,
    E: Debug
[src]

Set application data factory. This function is similar to .data() but it accepts data factory. Data object get constructed asynchronously during application initialization.

pub fn app_data<U: 'static>(self, ext: U) -> Self[src]

Set application level arbitrary data item.

Application data stored with App::app_data() method is available via HttpRequest::app_data() method at runtime.

This method could be used for storing Data<T> as well, in that case data could be accessed by using Data<T> extractor.

pub fn configure<F>(self, f: F) -> Self where
    F: FnOnce(&mut ServiceConfig), 
[src]

Run external configuration as part of the application building process

This function is useful for moving parts of configuration to a different module or even library. For example, some of the resource's configuration could be moved to different module.

use actix_web::{web, middleware, App, HttpResponse};

// this function could be located in different module
fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(web::resource("/test")
        .route(web::get().to(|| HttpResponse::Ok()))
        .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
    );
}

fn main() {
    let app = App::new()
        .wrap(middleware::Logger::default())
        .configure(config)  // <- register resources
        .route("/index.html", web::get().to(|| HttpResponse::Ok()));
}

pub fn route(self, path: &str, route: Route) -> Self[src]

Configure route for a specific path.

This is a simplified version of the App::service() method. This method can be used multiple times with same path, in that case multiple resources with one route would be registered for same resource path.

use actix_web::{web, App, HttpResponse};

async fn index(data: web::Path<(String, String)>) -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new()
        .route("/test1", web::get().to(index))
        .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()));
}

pub fn service<F>(self, factory: F) -> Self where
    F: HttpServiceFactory + 'static, 
[src]

Register http service.

Http service is any type that implements HttpServiceFactory trait.

Actix web provides several services implementations:

  • Resource is an entry in resource table which corresponds to requested URL.
  • Scope is a set of resources with common root path.
  • "StaticFiles" is a service for static files support

pub fn default_service<F, U>(self, f: F) -> Self where
    F: IntoServiceFactory<U, ServiceRequest>,
    U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static,
    U::InitError: Debug
[src]

Default service to be used if no matching resource could be found.

It is possible to use services like Resource, Route.

use actix_web::{web, App, HttpResponse};

async fn index() -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new()
        .service(
            web::resource("/index.html").route(web::get().to(index)))
        .default_service(
            web::route().to(|| HttpResponse::NotFound()));
}

It is also possible to use static files as default service.

use actix_web::{web, App, HttpResponse};

fn main() {
    let app = App::new()
        .service(
            web::resource("/index.html").to(|| HttpResponse::Ok()))
        .default_service(
            web::to(|| HttpResponse::NotFound())
        );
}

pub fn external_resource<N, U>(self, name: N, url: U) -> Self where
    N: AsRef<str>,
    U: AsRef<str>, 
[src]

Register an external resource.

External resources are useful for URL generation purposes only and are never considered for matching at request time. Calls to HttpRequest::url_for() will work as expected.

use actix_web::{web, App, HttpRequest, HttpResponse, Result};

async fn index(req: HttpRequest) -> Result<HttpResponse> {
    let url = req.url_for("youtube", &["asdlkjqme"])?;
    assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
    Ok(HttpResponse::Ok().into())
}

fn main() {
    let app = App::new()
        .service(web::resource("/index.html").route(
            web::get().to(index)))
        .external_resource("youtube", "https://youtube.com/watch/{video_id}");
}

pub fn wrap<M, B1>(
    self,
    mw: M
) -> App<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
    M: Transform<T::Service, ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>,
    B1: MessageBody
[src]

Registers middleware, in the form of a middleware component (type), that runs during inbound and/or outbound processing in the request life-cycle (request -> response), modifying request/response as necessary, across all requests managed by the Application.

Use middleware when you need to read or modify every request or response in some way.

Notice that the keyword for registering middleware is wrap. As you register middleware using wrap in the App builder, imagine wrapping layers around an inner App. The first middleware layer exposed to a Request is the outermost layer-- the last registered in the builder chain. Consequently, the first middleware registered in the builder chain is the last to execute during request processing.

use actix_service::Service;
use actix_web::{middleware, web, App};
use actix_web::http::{header::CONTENT_TYPE, HeaderValue};

async fn index() -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new()
        .wrap(middleware::Logger::default())
        .route("/index.html", web::get().to(index));
}

pub fn wrap_fn<B1, F, R>(
    self,
    mw: F
) -> App<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
    B1: MessageBody,
    F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone,
    R: Future<Output = Result<ServiceResponse<B1>, Error>>, 
[src]

Registers middleware, in the form of a closure, that runs during inbound and/or outbound processing in the request life-cycle (request -> response), modifying request/response as necessary, across all requests managed by the Application.

Use middleware when you need to read or modify every request or response in some way.

use actix_service::Service;
use actix_web::{web, App};
use actix_web::http::{header::CONTENT_TYPE, HeaderValue};

async fn index() -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new()
        .wrap_fn(|req, srv| {
            let fut = srv.call(req);
            async {
                let mut res = fut.await?;
                res.headers_mut().insert(
                   CONTENT_TYPE, HeaderValue::from_static("text/plain"),
                );
                Ok(res)
            }
        })
        .route("/index.html", web::get().to(index));
}

Auto Trait Implementations

impl<T, B> !RefUnwindSafe for App<T, B>[src]

impl<T, B> !Send for App<T, B>[src]

impl<T, B> !Sync for App<T, B>[src]

impl<T, B> Unpin for App<T, B> where
    B: Unpin,
    T: Unpin
[src]

impl<T, B> !UnwindSafe for App<T, B>[src]

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,