2017-12-02 07:06:15 +00:00
|
|
|
# Application
|
2017-11-28 20:44:59 +00:00
|
|
|
|
|
|
|
Actix web provides some primitives to build web servers and applications with Rust.
|
|
|
|
It provides routing, middlewares, pre-processing of requests, and post-processing of responses,
|
|
|
|
websocket protcol handling, multipart streams, etc.
|
|
|
|
|
|
|
|
All actix web server is built around `Application` instance.
|
2017-12-11 22:16:29 +00:00
|
|
|
It is used for registering routes for resources, middlewares.
|
|
|
|
Also it stores application specific state that is shared accross all handlers
|
2017-11-28 20:44:59 +00:00
|
|
|
within same application.
|
|
|
|
|
|
|
|
Application acts as namespace for all routes, i.e all routes for specific application
|
|
|
|
has same url path prefix:
|
|
|
|
|
|
|
|
```rust,ignore
|
2017-12-04 21:32:05 +00:00
|
|
|
# extern crate actix_web;
|
|
|
|
# extern crate tokio_core;
|
|
|
|
# use actix_web::*;
|
|
|
|
# fn index(req: HttpRequest) -> &'static str {
|
|
|
|
# "Hello world!"
|
|
|
|
# }
|
|
|
|
# fn main() {
|
2017-12-11 22:16:29 +00:00
|
|
|
let app = Application::new()
|
|
|
|
.prefix("/prefix")
|
2017-12-04 22:07:53 +00:00
|
|
|
.resource("/index.html", |r| r.method(Method::GET).f(index))
|
2017-11-28 20:44:59 +00:00
|
|
|
.finish()
|
2017-12-04 21:32:05 +00:00
|
|
|
# }
|
2017-11-28 20:44:59 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
In this example application with `/prefix` prefix and `index.html` resource
|
|
|
|
get created. This resource is available as on `/prefix/index.html` url.
|
2017-12-11 22:16:29 +00:00
|
|
|
For more information check
|
|
|
|
[*URL Matching*](./qs_5.html#using-a-application-prefix-to-compose-applications) section.
|
2017-12-02 07:32:15 +00:00
|
|
|
|
|
|
|
Multiple applications could be served with one server:
|
|
|
|
|
|
|
|
```rust
|
2017-12-04 21:32:05 +00:00
|
|
|
# extern crate actix_web;
|
|
|
|
# extern crate tokio_core;
|
2017-12-11 22:16:29 +00:00
|
|
|
# use tokio_core::net::TcpStream;
|
|
|
|
# use std::net::SocketAddr;
|
2017-12-02 07:32:15 +00:00
|
|
|
use actix_web::*;
|
|
|
|
|
|
|
|
fn main() {
|
2017-12-13 01:21:00 +00:00
|
|
|
HttpServer::<TcpStream, SocketAddr, _, _>::new(|| vec![
|
2017-12-11 22:16:29 +00:00
|
|
|
Application::new()
|
|
|
|
.prefix("/app1")
|
2017-12-06 19:00:39 +00:00
|
|
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
2017-12-11 22:16:29 +00:00
|
|
|
Application::new()
|
|
|
|
.prefix("/app2")
|
2017-12-06 19:00:39 +00:00
|
|
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
2017-12-11 22:16:29 +00:00
|
|
|
Application::new()
|
2017-12-06 19:00:39 +00:00
|
|
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
2017-12-02 07:32:15 +00:00
|
|
|
]);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
All `/app1` requests route to first application, `/app2` to second and then all other to third.
|