# [−][src]Struct actix_web::App

    pub struct App<S = ()> { /* fields omitted */ }

Structure that follows the builder pattern for building application instances.

## Methods

###

`impl App<()>`

[src]

####

`pub fn new() -> App<()>`

[src]

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

###

`impl<S> App<S> where S: 'static,`

[src]

####

`pub fn with_state(state: S) -> App<S>`

[src]

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

State is shared with all resources within same application and could be accessed with `HttpRequest::state()` method.

Note: http server accepts an application factory rather than an application instance. Http server constructs an application instance for each thread, thus application state must be constructed multiple times. If you want to share state between different threads, a shared object should be used, e.g. `Arc`. Application state does not need to be `Send` or `Sync`.

####

`pub fn state(&self) -> &S`

[src]

Get reference to the application state

####

`pub fn prefix<P: Into<String>>(self, prefix: P) -> App<S>`

[src]

Set application prefix.

Only requests that match the application's prefix get processed by this application.

The application prefix always contains a leading slash (`/`). If the supplied prefix does not contain leading slash, it is inserted.

Prefix should consist of valid path segments. i.e for an application with the prefix `/app` any request with the paths `/app`, `/app/` or `/app/test` would match, but the path `/application` would not.

In the following example only requests with an `/app/` path prefix get handled. Requests with path `/app/test/` would be handled, while requests with the paths `/application` or `/other/...` would return `NOT FOUND`. It is also possible to handle `/app` path, to do this you can register resource for empty string `""`

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

    fn main() {
        let app = App::new()
            .prefix("/app")
            .resource("", |r| r.f(|_| HttpResponse::Ok()))  // <- handle `/app` path
            .resource("/", |r| r.f(|_| HttpResponse::Ok())) // <- handle `/app/` path
            .resource("/test", |r| {
                r.get().f(|_| HttpResponse::Ok());
                r.head().f(|_| HttpResponse::MethodNotAllowed());
            })
            .finish();
    }

####

`pub fn filter<T: Predicate<S> + 'static>(self, p: T) -> App<S>`

[src]

Add match predicate to application.

    App::new()
        .filter(pred::Host("www.rust-lang.org"))
        .resource("/path", |r| r.f(|_| HttpResponse::Ok()))

####

`pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> where F: WithFactory<T, S, R>, R: Responder + 'static, T: FromRequest<S> + 'static,`

[src]

Configure route for a specific path.

This is a simplified version of the `App::resource()` method. Handler functions need to accept one request extractor argument.

This method could be called multiple times, in that case multiple routes would be registered for same resource path.

    use actix_web::{http, App, HttpRequest, HttpResponse};

    fn main() {
        let app = App::new()
            .route("/test", http::Method::GET, |_: HttpRequest| {
                HttpResponse::Ok()
            })
            .route("/test", http::Method::POST, |_: HttpRequest| {
                HttpResponse::MethodNotAllowed()
            });
    }

####

`pub fn scope<F>(self, path: &str, f: F) -> App<S> where F: FnOnce(Scope<S>) -> Scope<S>,`

[src]

Configure scope for common root path.

Scopes collect multiple paths under a common path prefix. Scope path can contain variable path segments as resources.

    use actix_web::{http, App, HttpRequest, HttpResponse};

    fn main() {
        let app = App::new().scope("/{project_id}", |scope| {
            scope
                .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
                .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
                .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
        });
    }

In the above example, three routes get added:

- /{project_id}/path1
- /{project_id}/path2
- /{project_id}/path3

####

`pub fn resource<F, R>(self, path: &str, f: F) -> App<S> where F: FnOnce(&mut Resource<S>) -> R + 'static,`

[src]

Configure resource for a specific path.

Resources may have variable path segments. For example, a resource with the path `/a/{name}/c` would match all incoming requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`.

A variable segment is specified in the form `{identifier}`, where the identifier can be used later in a request handler to access the matched value for that segment. This is done by looking up the identifier in the `Params` object returned by `HttpRequest.match_info()` method.

By default, each segment matches the regular expression `[^{}/]+`.

You can also specify a custom regex in the form `{identifier:regex}`:

For instance, to route `GET`-requests on any route matching `/users/{userid}/{friend}` and store `userid` and `friend` in the exposed `Params` object:

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

    fn main() {
        let app = App::new().resource("/users/{userid}/{friend}", |r| {
            r.get().f(|_| HttpResponse::Ok());
            r.head().f(|_| HttpResponse::MethodNotAllowed());
        });
    }

####

`pub fn default_resource<F, R>(self, f: F) -> App<S> where F: FnOnce(&mut Resource<S>) -> R + 'static,`

[src]

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

####

`pub fn default_encoding(self, encoding: ContentEncoding) -> App<S>`

[src]

Set default content encoding. `ContentEncoding::Auto` is set by default.

####

`pub fn external_resource<T, U>(self, name: T, url: U) -> App<S> where T: 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::{App, HttpRequest, HttpResponse, Result};

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

    fn main() {
        let app = App::new()
            .resource("/index.html", |r| r.get().f(index))
            .external_resource("youtube", "https://youtube.com/watch/{video_id}")
            .finish();
    }

####

`pub fn handler<H: Handler<S>>(self, path: &str, handler: H) -> App<S>`

[src]

Configure handler for specific path prefix.

A path prefix consists of valid path segments, i.e for the prefix `/app` any request with the paths `/app`, `/app/` or `/app/test` would match, but the path `/application` would not.

Path tail is available as `tail` parameter in request's match_dict.

    use actix_web::{http, App, HttpRequest, HttpResponse};

    fn main() {
        let app = App::new().handler("/app", |req: &HttpRequest| match *req.method() {
            http::Method::GET => HttpResponse::Ok(),
            http::Method::POST => HttpResponse::MethodNotAllowed(),
            _ => HttpResponse::NotFound(),
        });
    }

####

`pub fn middleware<M: Middleware<S>>(self, mw: M) -> App<S>`

[src]

Register a middleware.

####

`pub fn configure<F>(self, cfg: F) -> App<S> where F: Fn(App<S>) -> App<S>,`

[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 event library. For example we can move some of the resources' configuration to different module.

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

    // this function could be located in different module
    fn config(app: App) -> App {
        app.resource("/test", |r| {
            r.get().f(|_| HttpResponse::Ok());
            r.head().f(|_| HttpResponse::MethodNotAllowed());
        })
    }

    fn main() {
        let app = App::new()
            .middleware(middleware::Logger::default())
            .configure(config)  // <- register resources
            .handler("/static", fs::StaticFiles::new(".").unwrap());
    }

####

`pub fn finish(&mut self) -> HttpApplication<S>`

[src]

Finish application configuration and create `HttpHandler` object.

####

`pub fn boxed(self) -> Box<HttpHandler<Task = Box<HttpHandlerTask>>>`

[src]

Convenience method for creating `Box<HttpHandler>` instances.

This method is useful if you need to register multiple application instances with different state.

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

    struct State1;

    struct State2;

    fn main() {
        server::new(|| {
            vec![
                App::with_state(State1)
                    .prefix("/app1")
                    .resource("/", |r| r.f(|r| HttpResponse::Ok()))
                    .boxed(),
                App::with_state(State2)
                    .prefix("/app2")
                    .resource("/", |r| r.f(|r| HttpResponse::Ok()))
                    .boxed(),
            ]
        }).bind("127.0.0.1:8080")
            .unwrap()
            .run()
    }

## Trait Implementations

###

`impl<S: 'static> IntoHttpHandler for App<S>`

[src]

#### `type Handler = HttpApplication<S>`

The associated type which is result of conversion.

####

`fn into_handler(self) -> HttpApplication<S>`

[src]

Convert into `HttpHandler` object.

###

`impl<'a, S: 'static> IntoHttpHandler for &'a mut App<S>`

[src]

#### `type Handler = HttpApplication<S>`

The associated type which is result of conversion.

####

`fn into_handler(self) -> HttpApplication<S>`

[src]

Convert into `HttpHandler` object.

###

`impl Default for App<()>`

[src]

####

`fn default() -> Self`

[src]

Returns the "default value" for a type. Read more

## Auto Trait Implementations

###

`impl<S = ()> !Send for App<S>`

###

`impl<S = ()> !Sync for App<S>`

## Blanket Implementations

###

`impl<T> From for T`

[src]

####

`fn from(t: T) -> T`

[src]

Performs the conversion.

###

`impl<I> IntoIterator for I where I: Iterator,`

[src]

#### `type Item = <I as Iterator>::Item`

The type of the elements being iterated over.

#### `type IntoIter = I`

Which kind of iterator are we turning this into?

####

`fn into_iter(self) -> I`

[src]

Creates an iterator from a value. Read more

###

`impl<T, U> Into for T where U: From<T>,`

[src]

####

`fn into(self) -> U`

[src]

Performs the conversion.

###

`impl<T, U> TryFrom for T where T: From<U>,`

[src]

#### `type Error = !`

🔬 This is a nightly-only experimental API. (`try_from`)

The type returned in the event of a conversion error.

####

`fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>`

[src]

🔬 This is a nightly-only experimental API. (`try_from`)

Performs the conversion.

###

`impl<T> Borrow for T where T: ?Sized,`

[src]

####

`fn borrow(&self) -> &T`

[src]

Immutably borrows from an owned value. Read more

###

`impl<T> BorrowMut for T where T: ?Sized,`

[src]

####

`fn borrow_mut(&mut self) -> &mut T`

[src]

Mutably borrows from an owned value. Read more

###

`impl<T, U> TryInto for T where U: TryFrom<T>,`

[src]

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

🔬 This is a nightly-only experimental API. (`try_from`)

The type returned in the event of a conversion error.

####

`fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>`

[src]

🔬 This is a nightly-only experimental API. (`try_from`)

Performs the conversion.

###

`impl<T> Any for T where T: 'static + ?Sized,`

[src]

####

`fn get_type_id(&self) -> TypeId`

[src]

🔬 This is a nightly-only experimental API. (`get_type_id`)

this method will likely be replaced by an associated static

Gets the `TypeId` of `self`. Read more

###

`impl<T> Erased for T`

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)