[][src]Struct actix_web::App

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

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

Methods

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: NewService<Config = (), Request = ServiceRequest, 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. Application data does not need to be Send or Sync.

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

struct MyData {
    counter: Cell<usize>,
}

fn index(data: web::Data<MyData>) {
    data.counter.set(data.counter.get() + 1);
}

fn main() {
    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>(self, data: F) -> Self where
    F: Fn() -> Out + 'static,
    Out: IntoFuture + 'static,
    Out::Error: 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 register_data<U: 'static>(self, data: Data<U>) -> Self[src]

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

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};

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 hostname(self, val: &str) -> Self[src]

Set server host name.

Host name is used by application router as a hostname for url generation. Check [ConnectionInfo](./dev/struct.ConnectionInfo. html#method.host) documentation for more information.

By default host name is set to a "localhost" value.

pub fn default_service<F, U>(self, f: F) -> Self where
    F: IntoNewService<U>,
    U: NewService<Config = (), Request = ServiceRequest, 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};

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};

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, F>(
    self,
    mw: F
) -> App<impl NewService<Config = (), Request = ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
    M: Transform<T::Service, Request = ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>,
    B1: MessageBody,
    F: IntoTransform<M, T::Service>, 
[src]

Registers middleware, in the form of a middleware component (type), that runs during inbound and/or outbound processing in the request lifecycle (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};

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 NewService<Config = (), Request = ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
    B1: MessageBody,
    F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone,
    R: IntoFuture<Item = ServiceResponse<B1>, Error = Error>, 
[src]

Registers middleware, in the form of a closure, that runs during inbound and/or outbound processing in the request lifecycle (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};

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

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

Auto Trait Implementations

impl<T, B> !Send for App<T, B>

impl<T, B> Unpin for App<T, B> where
    B: Unpin,
    T: Unpin

impl<T, B> !Sync for App<T, B>

impl<T, B> !UnwindSafe for App<T, B>

impl<T, B> !RefUnwindSafe for App<T, B>

Blanket Implementations

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

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

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<T> Borrow<T> for T where
    T: ?Sized
[src]

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

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

impl<T> Erased for T

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