diff --git a/.appveyor.yml b/.appveyor.yml
index 69165cf5c..e1fa120d4 100644
--- a/.appveyor.yml
+++ b/.appveyor.yml
@@ -3,6 +3,15 @@ environment:
PROJECT_NAME: actix
matrix:
# Stable channel
+ - TARGET: i686-pc-windows-gnu
+ CHANNEL: 1.20.0
+ - TARGET: i686-pc-windows-msvc
+ CHANNEL: 1.20.0
+ - TARGET: x86_64-pc-windows-gnu
+ CHANNEL: 1.20.0
+ - TARGET: x86_64-pc-windows-msvc
+ CHANNEL: 1.20.0
+ # Stable channel
- TARGET: i686-pc-windows-gnu
CHANNEL: stable
- TARGET: i686-pc-windows-msvc
@@ -22,13 +31,13 @@ environment:
CHANNEL: beta
# Nightly channel
- TARGET: i686-pc-windows-gnu
- CHANNEL: nightly
+ CHANNEL: nightly-2017-12-21
- TARGET: i686-pc-windows-msvc
- CHANNEL: nightly
+ CHANNEL: nightly-2017-12-21
- TARGET: x86_64-pc-windows-gnu
- CHANNEL: nightly
+ CHANNEL: nightly-2017-12-21
- TARGET: x86_64-pc-windows-msvc
- CHANNEL: nightly
+ CHANNEL: nightly-2017-12-21
# Install Rust and Cargo
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
diff --git a/.travis.yml b/.travis.yml
index a1b3c431e..4642eb065 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,7 @@ rust:
- 1.20.0
- stable
- beta
- - nightly
+ - nightly-2018-01-03
sudo: required
dist: trusty
@@ -28,7 +28,28 @@ before_script:
- export PATH=$PATH:~/.cargo/bin
script:
- - USE_SKEPTIC=1 cargo test --features=alpn
+ - |
+ if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then
+ USE_SKEPTIC=1 cargo test --features=alpn
+ else
+ cargo test --features=alpn
+ fi
+
+ - |
+ if [[ "$TRAVIS_RUST_VERSION" == "1.20.0" ]]; then
+ cd examples/basics && cargo check && cd ../..
+ cd examples/hello-world && cargo check && cd ../..
+ cd examples/multipart && cargo check && cd ../..
+ cd examples/json && cargo check && cd ../..
+ cd examples/template_tera && cargo check && cd ../..
+ fi
+ - |
+ if [[ "$TRAVIS_RUST_VERSION" == "beta" ]]; then
+ cd examples/diesel && cargo check && cd ../..
+ cd examples/tls && cargo check && cd ../..
+ cd examples/websocket-chat && cargo check && cd ../..
+ cd examples/websocket && cargo check && cd ../..
+ fi
- |
if [[ "$TRAVIS_RUST_VERSION" == "nightly" && $CLIPPY ]]; then
cargo clippy
@@ -37,7 +58,7 @@ script:
# Upload docs
after_success:
- |
- if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
+ if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "nightly-2018-01-03" ]]; then
cargo doc --features alpn --no-deps &&
echo "" > target/doc/index.html &&
cargo install mdbook &&
@@ -49,18 +70,8 @@ after_success:
- |
if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_RUST_VERSION" == "stable" ]]; then
- wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz &&
- tar xzf master.tar.gz &&
- cd kcov-master &&
- mkdir build &&
- cd build &&
- cmake .. &&
- make &&
- make install DESTDIR=../../kcov-build &&
- cd ../.. &&
- rm -rf kcov-master &&
- for file in target/debug/actix_web-*[^\.d]; do mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; done &&
- for file in target/debug/test_*[^\.d]; do mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; done &&
- bash <(curl -s https://codecov.io/bash) &&
+ bash <(curl https://raw.githubusercontent.com/xd009642/tarpaulin/master/travis-install.sh)
+ USE_SKEPTIC=1 cargo tarpaulin --out Xml
+ bash <(curl -s https://codecov.io/bash)
echo "Uploaded code coverage"
fi
diff --git a/CHANGES.md b/CHANGES.md
index 836b16b3c..22b422667 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -15,6 +15,10 @@
* Content compression/decompression (br, gzip, deflate)
+* Server multi-threading
+
+* Gracefull shutdown support
+
## 0.2.1 (2017-11-03)
diff --git a/Cargo.toml b/Cargo.toml
index bb4b7b932..5f9f27734 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,13 +4,13 @@ version = "0.3.0"
authors = ["Nikolay Kim "]
description = "Actix web framework"
readme = "README.md"
-keywords = ["http", "http2", "web", "async", "futures"]
+keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://github.com/actix/actix-web"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-web/"
categories = ["network-programming", "asynchronous",
"web-programming::http-server", "web-programming::websocket"]
-license = "Apache-2.0"
+license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
build = "build.rs"
@@ -42,7 +42,6 @@ httparse = "0.1"
http-range = "0.1"
mime = "0.3"
mime_guess = "1.8"
-cookie = { version="0.10", features=["percent-encode", "secure"] }
regex = "0.2"
sha1 = "0.2"
url = "1.5"
@@ -52,10 +51,17 @@ serde_json = "1.0"
flate2 = "0.2"
brotli2 = "^0.3.2"
percent-encoding = "1.0"
+smallvec = "0.6"
+bitflags = "1.0"
+num_cpus = "1.0"
-# redis-async = { git="https://github.com/benashford/redis-async-rs" }
+# temp solution
+# cookie = { version="0.10", features=["percent-encode", "secure"] }
+cookie = { git="https://github.com/alexcrichton/cookie-rs.git", features=["percent-encode", "secure"] }
-# tokio
+# io
+mio = "0.6"
+net2 = "0.2"
bytes = "0.4"
futures = "0.1"
tokio-io = "0.1"
@@ -71,11 +77,8 @@ tokio-tls = { version="0.1", optional = true }
tokio-openssl = { version="0.1", optional = true }
[dependencies.actix]
-version = "^0.3.1"
-#path = "../actix"
-#git = "https://github.com/actix/actix.git"
-default-features = false
-features = []
+#version = "^0.4.2"
+git = "https://github.com/actix/actix.git"
[dependencies.openssl]
version = "0.9"
@@ -89,10 +92,24 @@ serde_derive = "1.0"
[build-dependencies]
skeptic = "0.13"
-serde_derive = "1.0"
version_check = "0.1"
[profile.release]
lto = true
opt-level = 3
-debug = true
+# debug = true
+
+[workspace]
+members = [
+ "./",
+ "examples/basics",
+ "examples/diesel",
+ "examples/json",
+ "examples/hello-world",
+ "examples/multipart",
+ "examples/state",
+ "examples/template_tera",
+ "examples/tls",
+ "examples/websocket",
+ "examples/websocket-chat",
+]
diff --git a/LICENSE b/LICENSE-APACHE
similarity index 100%
rename from LICENSE
rename to LICENSE-APACHE
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 000000000..410ce45a4
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2017 Nikilay Kim
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/Makefile b/Makefile
index fc6071083..fdc3cbbc0 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
.PHONY: default build test doc book clean
-CARGO_FLAGS := --features "$(FEATURES)"
+CARGO_FLAGS := --features "$(FEATURES) alpn"
default: test
diff --git a/README.md b/README.md
index ff19d5ede..124fb9e83 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,25 @@
-# Actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![Build status](https://ci.appveyor.com/api/projects/status/kkdb4yce7qhm5w85/branch/master?svg=true)](https://ci.appveyor.com/project/fafhrd91/actix-web-hdy9d/branch/master) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](http://meritbadge.herokuapp.com/actix-web)](https://crates.io/crates/actix-web)
+# Actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![Build status](https://ci.appveyor.com/api/projects/status/kkdb4yce7qhm5w85/branch/master?svg=true)](https://ci.appveyor.com/project/fafhrd91/actix-web-hdy9d/branch/master) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](http://meritbadge.herokuapp.com/actix-web)](https://crates.io/crates/actix-web) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-Actix web is a fast, down-to-earth, open source rust web framework.
+Actix web is a small, fast, down-to-earth, open source rust web framework.
+
+```rust,ignore
+extern crate actix_web;
+use actix_web::*;
+
+fn index(req: HttpRequest) -> String {
+ format!("Hello {}!", &req.match_info()["name"])
+}
+
+fn main() {
+ HttpServer::new(
+ || Application::new()
+ .resource("/{name}", |r| r.f(index)))
+ .bind("127.0.0.1:8080").unwrap()
+ .run();
+}
+```
+
+## Documentation
* [User Guide](http://actix.github.io/actix-web/guide/)
* [API Documentation (Development)](http://actix.github.io/actix-web/actix_web/)
@@ -8,111 +27,45 @@ Actix web is a fast, down-to-earth, open source rust web framework.
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
* Minimum supported Rust version: 1.20 or later
----
-
-Actix web is licensed under the [Apache-2.0 license](http://opensource.org/licenses/APACHE-2.0).
-
## Features
- * Supported HTTP/1 and HTTP/2 protocols
- * Streaming and pipelining
- * Keep-alive and slow requests handling
- * [WebSockets](https://actix.github.io/actix-web/actix_web/ws/index.html)
- * Transparent content compression/decompression (br, gzip, deflate)
- * Configurable request routing
- * Multipart streams
- * Middlewares (Logger, Session included)
+* Supported *HTTP/1.x* and *HTTP/2.0* protocols
+* Streaming and pipelining
+* Keep-alive and slow requests handling
+* [WebSockets](https://actix.github.io/actix-web/actix_web/ws/index.html)
+* Transparent content compression/decompression (br, gzip, deflate)
+* Configurable request routing
+* Graceful server shutdown
+* Multipart streams
+* Middlewares ([Logger](https://actix.github.io/actix-web/guide/qs_10.html#logging),
+ [Session](https://actix.github.io/actix-web/guide/qs_10.html#user-sessions),
+ [DefaultHeaders](https://actix.github.io/actix-web/guide/qs_10.html#default-headers))
+* Built on top of [Actix](https://github.com/actix/actix).
-## Usage
+## Benchmarks
-To use `actix-web`, add this to your `Cargo.toml`:
+Some basic benchmarks could be found in this [respository](https://github.com/fafhrd91/benchmarks).
-```toml
-[dependencies]
-actix-web = { git = "https://github.com/actix/actix-web" }
-```
+## Examples
-## HTTP/2
-
-Actix web automatically upgrades connection to `http/2` if possible.
-
-### Negotiation
-
-`HTTP/2` protocol over tls without prior knowlage requires
-[tls alpn](https://tools.ietf.org/html/rfc7301). At the moment only
-`rust-openssl` supports alpn.
-
-```toml
-[dependencies]
-actix-web = { git = "https://github.com/actix/actix-web", features=["alpn"] }
-```
-
-Upgrade to `http/2` schema described in
-[rfc section 3.2](https://http2.github.io/http2-spec/#rfc.section.3.2) is not supported.
-Starting `http/2` with prior knowledge is supported for both clear text connection
-and tls connection. [rfc section 3.4](https://http2.github.io/http2-spec/#rfc.section.3.4)
-
-[tls example](https://github.com/actix/actix-web/tree/master/examples/tls)
-
-## Example
-
-* [Basic](https://github.com/actix/actix-web/tree/master/examples/basic.rs)
-* [Stateful](https://github.com/actix/actix-web/tree/master/examples/state.rs)
-* [Mulitpart streams](https://github.com/actix/actix-web/tree/master/examples/multipart)
-* [Simple websocket session](https://github.com/actix/actix-web/tree/master/examples/websocket.rs)
-* [Tcp/Websocket chat](https://github.com/actix/actix-web/tree/master/examples/websocket-chat)
+* [Basic](https://github.com/actix/actix-web/tree/master/examples/basic/)
+* [Stateful](https://github.com/actix/actix-web/tree/master/examples/state/)
+* [Mulitpart streams](https://github.com/actix/actix-web/tree/master/examples/multipart/)
+* [Simple websocket session](https://github.com/actix/actix-web/tree/master/examples/websocket/)
+* [Tera templates](https://github.com/actix/actix-web/tree/master/examples/template_tera/)
+* [Diesel integration](https://github.com/actix/actix-web/tree/master/examples/diesel/)
+* [SSL / HTTP/2.0](https://github.com/actix/actix-web/tree/master/examples/tls/)
+* [Tcp/Websocket chat](https://github.com/actix/actix-web/tree/master/examples/websocket-chat/)
* [SockJS Server](https://github.com/actix/actix-sockjs)
+* [Json](https://github.com/actix/actix-web/tree/master/examples/json/)
+## License
-```rust
-extern crate actix;
-extern crate actix_web;
-extern crate env_logger;
+This project is licensed under either of
-use actix::*;
-use actix_web::*;
+* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0))
+* MIT license ([LICENSE-MIT](LICENSE-MIT) or [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT))
-struct MyWebSocket;
+at your option.
-/// Actor with http context
-impl Actor for MyWebSocket {
- type Context = HttpContext;
-}
-
-/// Standard actix's stream handler for a stream of `ws::Message`
-impl StreamHandler for MyWebSocket {}
-impl Handler for MyWebSocket {
- fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context)
- -> Response
- {
- // process websocket messages
- println!("WS: {:?}", msg);
- match msg {
- ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg),
- ws::Message::Text(text) => ws::WsWriter::text(ctx, &text),
- ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin),
- ws::Message::Closed | ws::Message::Error => {
- ctx.stop();
- }
- _ => (),
- }
- Self::empty()
- }
-}
-
-fn main() {
- ::std::env::set_var("RUST_LOG", "actix_web=info");
- let _ = env_logger::init();
- let sys = actix::System::new("ws-example");
-
- HttpServer::new(
- Application::default("/")
- .middleware(middlewares::Logger::default()) // <- register logger middleware
- .resource("/ws/", |r| r.get(|req| ws::start(req, MyWebSocket))) // <- websocket route
- .route("/", StaticFiles::new("examples/static/", true))) // <- server static files
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
-
- Arbiter::system().send(msgs::SystemExit(0));
- let _ = sys.run();
-}
-```
+[![Analytics](https://ga-beacon.appspot.com/UA-110322332-2/actix-web/readme?flat&useReferer)](https://github.com/igrigorik/ga-beacon)
diff --git a/build.rs b/build.rs
index dae9e0626..2346ab169 100644
--- a/build.rs
+++ b/build.rs
@@ -12,8 +12,19 @@ fn main() {
// generates doc tests for `README.md`.
skeptic::generate_doc_tests(
&["README.md",
+ "guide/src/qs_1.md",
"guide/src/qs_2.md",
"guide/src/qs_3.md",
+ "guide/src/qs_3_5.md",
+ "guide/src/qs_4.md",
+ "guide/src/qs_4_5.md",
+ "guide/src/qs_5.md",
+ "guide/src/qs_7.md",
+ "guide/src/qs_8.md",
+ "guide/src/qs_9.md",
+ "guide/src/qs_10.md",
+ "guide/src/qs_12.md",
+ "guide/src/qs_13.md",
]);
} else {
let _ = fs::File::create(f);
diff --git a/examples/basic.rs b/examples/basic.rs
deleted file mode 100644
index fc2a55355..000000000
--- a/examples/basic.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-#![allow(unused_variables)]
-#![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))]
-
-extern crate actix;
-extern crate actix_web;
-extern crate env_logger;
-extern crate futures;
-
-use actix_web::*;
-use actix_web::middlewares::RequestSession;
-use futures::future::{FutureResult, result};
-
-/// simple handler
-fn index(mut req: HttpRequest) -> Result {
- println!("{:?}", req);
- if let Ok(ch) = req.payload_mut().readany() {
- if let futures::Async::Ready(Some(d)) = ch {
- println!("{}", String::from_utf8_lossy(d.0.as_ref()));
- }
- }
-
- // session
- if let Some(count) = req.session().get::("counter")? {
- println!("SESSION value: {}", count);
- req.session().set("counter", count+1)?;
- } else {
- req.session().set("counter", 1)?;
- }
-
- Ok(HttpResponse::Ok().into())
-}
-
-/// async handler
-fn index_async(req: HttpRequest) -> FutureResult
-{
- println!("{:?}", req);
-
- result(HttpResponse::Ok()
- .content_type("text/html")
- .body(format!("Hello {}!", req.match_info().get("name").unwrap()))
- .map_err(|e| e.into()))
-}
-
-/// handler with path parameters like `/user/{name}/`
-fn with_param(req: HttpRequest) -> Result
-{
- println!("{:?}", req);
-
- Ok(HttpResponse::Ok()
- .content_type("test/plain")
- .body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
-}
-
-fn main() {
- ::std::env::set_var("RUST_LOG", "actix_web=info");
- let _ = env_logger::init();
- let sys = actix::System::new("ws-example");
-
- HttpServer::new(
- Application::default("/")
- // enable logger
- .middleware(middlewares::Logger::default())
- // cookie session middleware
- .middleware(middlewares::SessionStorage::new(
- middlewares::CookieSessionBackend::build(&[0; 32])
- .secure(false)
- .finish()
- ))
- // register simple handle r, handle all methods
- .handler("/index.html", index)
- // with path parameters
- .resource("/user/{name}/", |r| r.handler(Method::GET, with_param))
- // async handler
- .resource("/async/{name}", |r| r.async(Method::GET, index_async))
- // redirect
- .resource("/", |r| r.handler(Method::GET, |req| {
- println!("{:?}", req);
-
- httpcodes::HTTPFound
- .build()
- .header("LOCATION", "/index.html")
- .body(Body::Empty)
- }))
- .handler("/test", |req| {
- match *req.method() {
- Method::GET => httpcodes::HTTPOk,
- Method::POST => httpcodes::HTTPMethodNotAllowed,
- _ => httpcodes::HTTPNotFound,
- }
- })
- // static files
- .route("/static", StaticFiles::new("examples/static/", true)))
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
-
- println!("Started http server: 127.0.0.1:8080");
- let _ = sys.run();
-}
diff --git a/examples/basics/Cargo.toml b/examples/basics/Cargo.toml
new file mode 100644
index 000000000..88b5f61e0
--- /dev/null
+++ b/examples/basics/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "basics"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+futures = "*"
+env_logger = "0.4"
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
diff --git a/examples/basics/README.md b/examples/basics/README.md
new file mode 100644
index 000000000..154fad9de
--- /dev/null
+++ b/examples/basics/README.md
@@ -0,0 +1,19 @@
+# basics
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/basics
+cargo run
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+- [http://localhost:8080/index.html](http://localhost:8080/index.html)
+- [http://localhost:8080/async/bob](http://localhost:8080/async/bob)
+- [http://localhost:8080/user/bob/](http://localhost:8080/user/bob/) plain/text download
+- [http://localhost:8080/test](http://localhost:8080/test) (return status switch GET or POST or other)
+- [http://localhost:8080/static/index.html](http://localhost:8080/static/index.html)
\ No newline at end of file
diff --git a/examples/basics/src/main.rs b/examples/basics/src/main.rs
new file mode 100644
index 000000000..68dc17f30
--- /dev/null
+++ b/examples/basics/src/main.rs
@@ -0,0 +1,146 @@
+#![allow(unused_variables)]
+#![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))]
+
+extern crate actix;
+extern crate actix_web;
+extern crate env_logger;
+extern crate futures;
+use futures::Stream;
+
+use actix_web::*;
+use actix_web::middleware::RequestSession;
+use futures::future::{FutureResult, result};
+
+/// favicon handler
+fn favicon(req: HttpRequest) -> Result {
+ Ok(fs::NamedFile::open("../static/favicon.ico")?)
+}
+
+/// simple index handler
+fn index(mut req: HttpRequest) -> Result {
+ println!("{:?}", req);
+
+ // example of ...
+ if let Ok(ch) = req.payload_mut().readany().poll() {
+ if let futures::Async::Ready(Some(d)) = ch {
+ println!("{}", String::from_utf8_lossy(d.as_ref()));
+ }
+ }
+
+ // session
+ let mut counter = 1;
+ if let Some(count) = req.session().get::("counter")? {
+ println!("SESSION value: {}", count);
+ counter = count + 1;
+ req.session().set("counter", counter)?;
+ } else {
+ req.session().set("counter", counter)?;
+ }
+
+ // html
+ let html = format!(r#"actix - basics
+
+ Welcome
+ session counter = {}
+
+"#, counter);
+
+ // response
+ Ok(HttpResponse::build(StatusCode::OK)
+ .content_type("text/html; charset=utf-8")
+ .body(&html).unwrap())
+
+}
+
+/// 404 handler
+fn p404(req: HttpRequest) -> Result {
+
+ // html
+ let html = format!(r#"actix - basics
+
+ back to home
+ 404
+
+"#);
+
+ // response
+ Ok(HttpResponse::build(StatusCode::NOT_FOUND)
+ .content_type("text/html; charset=utf-8")
+ .body(&html).unwrap())
+}
+
+
+/// async handler
+fn index_async(req: HttpRequest) -> FutureResult
+{
+ println!("{:?}", req);
+
+ result(HttpResponse::Ok()
+ .content_type("text/html")
+ .body(format!("Hello {}!", req.match_info().get("name").unwrap()))
+ .map_err(|e| e.into()))
+}
+
+/// handler with path parameters like `/user/{name}/`
+fn with_param(req: HttpRequest) -> Result
+{
+ println!("{:?}", req);
+
+ Ok(HttpResponse::Ok()
+ .content_type("test/plain")
+ .body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
+}
+
+fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
+ let _ = env_logger::init();
+ let sys = actix::System::new("basic-example");
+
+ let addr = HttpServer::new(
+ || Application::new()
+ // enable logger
+ .middleware(middleware::Logger::default())
+ // cookie session middleware
+ .middleware(middleware::SessionStorage::new(
+ middleware::CookieSessionBackend::build(&[0; 32])
+ .secure(false)
+ .finish()
+ ))
+ // register favicon
+ .resource("/favicon.ico", |r| r.f(favicon))
+ // register simple route, handle all methods
+ .resource("/index.html", |r| r.f(index))
+ // with path parameters
+ .resource("/user/{name}/", |r| r.method(Method::GET).f(with_param))
+ // async handler
+ .resource("/async/{name}", |r| r.method(Method::GET).a(index_async))
+ .resource("/test", |r| r.f(|req| {
+ match *req.method() {
+ Method::GET => httpcodes::HTTPOk,
+ Method::POST => httpcodes::HTTPMethodNotAllowed,
+ _ => httpcodes::HTTPNotFound,
+ }
+ }))
+ // static files
+ .handler("/static/", fs::StaticFiles::new("../static/", true))
+ // redirect
+ .resource("/", |r| r.method(Method::GET).f(|req| {
+ println!("{:?}", req);
+
+ HttpResponse::Found()
+ .header("LOCATION", "/index.html")
+ .finish()
+ }))
+ // default
+ .default_resource(|r| {
+ r.method(Method::GET).f(p404);
+ r.route().p(pred::Not(pred::Get())).f(|req| httpcodes::HTTPMethodNotAllowed);
+ }))
+
+ .bind("127.0.0.1:8080").expect("Can not bind to 127.0.0.1:8080")
+ .shutdown_timeout(0) // <- Set shutdown timeout to 0 seconds (default 60s)
+ .start();
+
+ println!("Starting http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
diff --git a/examples/diesel/.env b/examples/diesel/.env
new file mode 100644
index 000000000..1fbc5af72
--- /dev/null
+++ b/examples/diesel/.env
@@ -0,0 +1 @@
+DATABASE_URL=file:test.db
diff --git a/examples/diesel/Cargo.toml b/examples/diesel/Cargo.toml
new file mode 100644
index 000000000..eb6628375
--- /dev/null
+++ b/examples/diesel/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "diesel-example"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+env_logger = "0.4"
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
+
+futures = "0.1"
+uuid = { version = "0.5", features = ["serde", "v4"] }
+serde = "1.0"
+serde_json = "1.0"
+serde_derive = "1.0"
+
+diesel = { version = "1.0.0-beta1", features = ["sqlite"] }
+dotenv = "0.10"
diff --git a/examples/diesel/README.md b/examples/diesel/README.md
new file mode 100644
index 000000000..922ba1e3b
--- /dev/null
+++ b/examples/diesel/README.md
@@ -0,0 +1,43 @@
+# diesel
+
+Diesel's `Getting Started` guide using SQLite for Actix web
+
+## Usage
+
+### init database sqlite
+
+```bash
+cargo install diesel_cli --no-default-features --features sqlite
+cd actix-web/examples/diesel
+echo "DATABASE_URL=file:test.db" > .env
+diesel migration run
+```
+
+### server
+
+```bash
+# if ubuntu : sudo apt-get install libsqlite3-dev
+# if fedora : sudo dnf install libsqlite3x-devel
+cd actix-web/examples/diesel
+cargo run (or ``cargo watch -x run``)
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+[http://127.0.0.1:8080/NAME](http://127.0.0.1:8080/NAME)
+
+### sqlite client
+
+```bash
+# if ubuntu : sudo apt-get install sqlite3
+# if fedora : sudo dnf install sqlite3x
+sqlite3 test.db
+sqlite> .tables
+sqlite> select * from users;
+```
+
+
+## Postgresql
+
+You will also find another complete example of diesel+postgresql on [https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)
\ No newline at end of file
diff --git a/examples/diesel/migrations/20170124012402_create_users/down.sql b/examples/diesel/migrations/20170124012402_create_users/down.sql
new file mode 100644
index 000000000..9951735c4
--- /dev/null
+++ b/examples/diesel/migrations/20170124012402_create_users/down.sql
@@ -0,0 +1 @@
+DROP TABLE users
diff --git a/examples/diesel/migrations/20170124012402_create_users/up.sql b/examples/diesel/migrations/20170124012402_create_users/up.sql
new file mode 100644
index 000000000..d88d44fb7
--- /dev/null
+++ b/examples/diesel/migrations/20170124012402_create_users/up.sql
@@ -0,0 +1,4 @@
+CREATE TABLE users (
+ id VARCHAR NOT NULL PRIMARY KEY,
+ name VARCHAR NOT NULL
+)
diff --git a/examples/diesel/src/db.rs b/examples/diesel/src/db.rs
new file mode 100644
index 000000000..04daa6ed0
--- /dev/null
+++ b/examples/diesel/src/db.rs
@@ -0,0 +1,53 @@
+//! Db executor actor
+use uuid;
+use diesel;
+use actix_web::*;
+use actix::prelude::*;
+use diesel::prelude::*;
+
+use models;
+use schema;
+
+/// This is db executor actor. We are going to run 3 of them in parallele.
+pub struct DbExecutor(pub SqliteConnection);
+
+/// This is only message that this actor can handle, but it is easy to extend number of
+/// messages.
+pub struct CreateUser {
+ pub name: String,
+}
+
+impl ResponseType for CreateUser {
+ type Item = models::User;
+ type Error = Error;
+}
+
+impl Actor for DbExecutor {
+ type Context = SyncContext;
+}
+
+impl Handler for DbExecutor {
+ type Result = MessageResult;
+
+ fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
+ use self::schema::users::dsl::*;
+
+ let uuid = format!("{}", uuid::Uuid::new_v4());
+ let new_user = models::NewUser {
+ id: &uuid,
+ name: &msg.name,
+ };
+
+ diesel::insert_into(users)
+ .values(&new_user)
+ .execute(&self.0)
+ .expect("Error inserting person");
+
+ let mut items = users
+ .filter(id.eq(&uuid))
+ .load::(&self.0)
+ .expect("Error loading person");
+
+ Ok(items.pop().unwrap())
+ }
+}
diff --git a/examples/diesel/src/main.rs b/examples/diesel/src/main.rs
new file mode 100644
index 000000000..4c4bc4cda
--- /dev/null
+++ b/examples/diesel/src/main.rs
@@ -0,0 +1,73 @@
+//! Actix web diesel example
+//!
+//! Diesel does not support tokio, so we have to run it in separate threads.
+//! Actix supports sync actors by default, so we going to create sync actor that will
+//! use diesel. Technically sync actors are worker style actors, multiple of them
+//! can run in parallel and process messages from same queue.
+extern crate serde;
+extern crate serde_json;
+#[macro_use]
+extern crate serde_derive;
+#[macro_use]
+extern crate diesel;
+extern crate uuid;
+extern crate futures;
+extern crate actix;
+extern crate actix_web;
+extern crate env_logger;
+
+use actix::*;
+use actix_web::*;
+
+use diesel::prelude::*;
+use futures::future::Future;
+
+mod db;
+mod models;
+mod schema;
+
+use db::{CreateUser, DbExecutor};
+
+
+/// State with DbExecutor address
+struct State {
+ db: SyncAddress,
+}
+
+/// Async request handler
+fn index(req: HttpRequest) -> Box> {
+ let name = &req.match_info()["name"];
+
+ req.state().db.call_fut(CreateUser{name: name.to_owned()})
+ .from_err()
+ .and_then(|res| {
+ match res {
+ Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?),
+ Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
+ }
+ })
+ .responder()
+}
+
+fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
+ let _ = env_logger::init();
+ let sys = actix::System::new("diesel-example");
+
+ // Start db executor actors
+ let addr = SyncArbiter::start(3, || {
+ DbExecutor(SqliteConnection::establish("test.db").unwrap())
+ });
+
+ // Start http server
+ let _addr = HttpServer::new(move || {
+ Application::with_state(State{db: addr.clone()})
+ // enable logger
+ .middleware(middleware::Logger::default())
+ .resource("/{name}", |r| r.method(Method::GET).a(index))})
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
+
+ println!("Started http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
diff --git a/examples/diesel/src/models.rs b/examples/diesel/src/models.rs
new file mode 100644
index 000000000..315d59f13
--- /dev/null
+++ b/examples/diesel/src/models.rs
@@ -0,0 +1,14 @@
+use super::schema::users;
+
+#[derive(Serialize, Queryable)]
+pub struct User {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Insertable)]
+#[table_name = "users"]
+pub struct NewUser<'a> {
+ pub id: &'a str,
+ pub name: &'a str,
+}
diff --git a/examples/diesel/src/schema.rs b/examples/diesel/src/schema.rs
new file mode 100644
index 000000000..51aa40b89
--- /dev/null
+++ b/examples/diesel/src/schema.rs
@@ -0,0 +1,6 @@
+table! {
+ users (id) {
+ id -> Text,
+ name -> Text,
+ }
+}
diff --git a/examples/diesel/test.db b/examples/diesel/test.db
new file mode 100644
index 000000000..65e590a6e
Binary files /dev/null and b/examples/diesel/test.db differ
diff --git a/examples/hello-world/Cargo.toml b/examples/hello-world/Cargo.toml
new file mode 100644
index 000000000..4cb1f70f7
--- /dev/null
+++ b/examples/hello-world/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "hello-world"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+env_logger = "0.4"
+actix = "0.4"
+actix-web = { path = "../../" }
diff --git a/examples/hello-world/src/main.rs b/examples/hello-world/src/main.rs
new file mode 100644
index 000000000..5f1484bd2
--- /dev/null
+++ b/examples/hello-world/src/main.rs
@@ -0,0 +1,28 @@
+extern crate actix;
+extern crate actix_web;
+extern crate env_logger;
+
+use actix_web::*;
+
+
+fn index(_req: HttpRequest) -> &'static str {
+ "Hello world!"
+}
+
+fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
+ let _ = env_logger::init();
+ let sys = actix::System::new("ws-example");
+
+ let _addr = HttpServer::new(
+ || Application::new()
+ // enable logger
+ .middleware(middleware::Logger::default())
+ .resource("/index.html", |r| r.f(|_| "Hello world!"))
+ .resource("/", |r| r.f(index)))
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
+
+ println!("Started http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
diff --git a/examples/json/Cargo.toml b/examples/json/Cargo.toml
new file mode 100644
index 000000000..681b63450
--- /dev/null
+++ b/examples/json/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "json-example"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+bytes = "0.4"
+futures = "0.1"
+env_logger = "*"
+
+serde = "1.0"
+serde_json = "1.0"
+serde_derive = "1.0"
+json = "*"
+
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
diff --git a/examples/json/README.md b/examples/json/README.md
new file mode 100644
index 000000000..167c3909f
--- /dev/null
+++ b/examples/json/README.md
@@ -0,0 +1,48 @@
+# json
+
+Json's `Getting Started` guide using json (serde-json or json-rust) for Actix web
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/json
+cargo run
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+With [Postman](https://www.getpostman.com/) or [Rested](moz-extension://60daeb1c-5b1b-4afd-9842-0579ed34dfcb/dist/index.html)
+
+- POST / (embed serde-json):
+
+ - method : ``POST``
+ - url : ``http://127.0.0.1:8080/``
+ - header : ``Content-Type`` = ``application/json``
+ - body (raw) : ``{"name": "Test user", "number": 100}``
+
+- POST /manual (manual serde-json):
+
+ - method : ``POST``
+ - url : ``http://127.0.0.1:8080/manual``
+ - header : ``Content-Type`` = ``application/json``
+ - body (raw) : ``{"name": "Test user", "number": 100}``
+
+- POST /mjsonrust (manual json-rust):
+
+ - method : ``POST``
+ - url : ``http://127.0.0.1:8080/mjsonrust``
+ - header : ``Content-Type`` = ``application/json``
+ - body (raw) : ``{"name": "Test user", "number": 100}`` (you can also test ``{notjson}``)
+
+### python client
+
+- ``pip install aiohttp``
+- ``python client.py``
+
+if ubuntu :
+
+- ``pip3 install aiohttp``
+- ``python3 client.py``
diff --git a/examples/json/client.py b/examples/json/client.py
new file mode 100644
index 000000000..e89ffe096
--- /dev/null
+++ b/examples/json/client.py
@@ -0,0 +1,18 @@
+# This script could be used for actix-web multipart example test
+# just start server and run client.py
+
+import json
+import asyncio
+import aiohttp
+
+async def req():
+ resp = await aiohttp.ClientSession().request(
+ "post", 'http://localhost:8080/',
+ data=json.dumps({"name": "Test user", "number": 100}),
+ headers={"content-type": "application/json"})
+ print(str(resp))
+ print(await resp.text())
+ assert 200 == resp.status
+
+
+asyncio.get_event_loop().run_until_complete(req())
diff --git a/examples/json/src/main.rs b/examples/json/src/main.rs
new file mode 100644
index 000000000..719d74853
--- /dev/null
+++ b/examples/json/src/main.rs
@@ -0,0 +1,99 @@
+extern crate actix;
+extern crate actix_web;
+extern crate bytes;
+extern crate futures;
+extern crate env_logger;
+extern crate serde_json;
+#[macro_use] extern crate serde_derive;
+#[macro_use] extern crate json;
+
+use actix_web::*;
+
+use bytes::BytesMut;
+use futures::{Future, Stream};
+use json::JsonValue;
+
+#[derive(Debug, Serialize, Deserialize)]
+struct MyObj {
+ name: String,
+ number: i32,
+}
+
+/// This handler uses `HttpRequest::json()` for loading serde json object.
+fn index(req: HttpRequest) -> Box> {
+ req.json()
+ .from_err() // convert all errors into `Error`
+ .and_then(|val: MyObj| {
+ println!("model: {:?}", val);
+ Ok(httpcodes::HTTPOk.build().json(val)?) // <- send response
+ })
+ .responder()
+}
+
+
+const MAX_SIZE: usize = 262_144; // max payload size is 256k
+
+/// This handler manually load request payload and parse serde json
+fn index_manual(mut req: HttpRequest) -> Box> {
+ // readany() returns asynchronous stream of Bytes objects
+ req.payload_mut().readany()
+ // `Future::from_err` acts like `?` in that it coerces the error type from
+ // the future into the final error type
+ .from_err()
+
+ // `fold` will asynchronously read each chunk of the request body and
+ // call supplied closure, then it resolves to result of closure
+ .fold(BytesMut::new(), move |mut body, chunk| {
+ // limit max size of in-memory payload
+ if (body.len() + chunk.len()) > MAX_SIZE {
+ Err(error::ErrorBadRequest("overflow"))
+ } else {
+ body.extend_from_slice(&chunk);
+ Ok(body)
+ }
+ })
+ // `Future::and_then` can be used to merge an asynchronous workflow with a
+ // synchronous workflow
+ .and_then(|body| {
+ // body is loaded, now we can deserialize serde-json
+ let obj = serde_json::from_slice::(&body)?;
+ Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
+ })
+ .responder()
+}
+
+/// This handler manually load request payload and parse json-rust
+fn index_mjsonrust(mut req: HttpRequest) -> Box> {
+ req.payload_mut().readany().concat2()
+ .from_err()
+ .and_then(|body| {
+ // body is loaded, now we can deserialize json-rust
+ let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
+ let injson: JsonValue = match result { Ok(v) => v, Err(e) => object!{"err" => e.to_string() } };
+ Ok(HttpResponse::build(StatusCode::OK)
+ .content_type("application/json")
+ .body(injson.dump()).unwrap())
+
+ })
+ .responder()
+}
+
+fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
+ let _ = env_logger::init();
+ let sys = actix::System::new("json-example");
+
+ let addr = HttpServer::new(|| {
+ Application::new()
+ // enable logger
+ .middleware(middleware::Logger::default())
+ .resource("/manual", |r| r.method(Method::POST).f(index_manual))
+ .resource("/mjsonrust", |r| r.method(Method::POST).f(index_mjsonrust))
+ .resource("/", |r| r.method(Method::POST).f(index))})
+ .bind("127.0.0.1:8080").unwrap()
+ .shutdown_timeout(1)
+ .start();
+
+ println!("Started http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
diff --git a/examples/multipart/Cargo.toml b/examples/multipart/Cargo.toml
index 5cb2031df..32edbea61 100644
--- a/examples/multipart/Cargo.toml
+++ b/examples/multipart/Cargo.toml
@@ -2,6 +2,7 @@
name = "multipart-example"
version = "0.1.0"
authors = ["Nikolay Kim "]
+workspace = "../.."
[[bin]]
name = "multipart"
@@ -9,5 +10,6 @@ path = "src/main.rs"
[dependencies]
env_logger = "*"
-actix = "^0.3.1"
-actix-web = { git = "https://github.com/actix/actix-web.git" }
+futures = "0.1"
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
diff --git a/examples/multipart/README.md b/examples/multipart/README.md
new file mode 100644
index 000000000..348d28687
--- /dev/null
+++ b/examples/multipart/README.md
@@ -0,0 +1,24 @@
+# multipart
+
+Multipart's `Getting Started` guide for Actix web
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/multipart
+cargo run (or ``cargo watch -x run``)
+# Started http server: 127.0.0.1:8080
+```
+
+### client
+
+- ``pip install aiohttp``
+- ``python client.py``
+- you must see in server console multipart fields
+
+if ubuntu :
+
+- ``pip3 install aiohttp``
+- ``python3 client.py``
diff --git a/examples/multipart/client.py b/examples/multipart/client.py
index 35f97c1a6..afc07f17d 100644
--- a/examples/multipart/client.py
+++ b/examples/multipart/client.py
@@ -1,26 +1,28 @@
+# This script could be used for actix-web multipart example test
+# just start server and run client.py
+
import asyncio
import aiohttp
-
-def req1():
+async def req1():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
- resp = yield from aiohttp.request(
+ resp = await aiohttp.ClientSession().request(
"post", 'http://localhost:8080/multipart',
data=writer, headers=writer.headers)
print(resp)
assert 200 == resp.status
-def req2():
+async def req2():
with aiohttp.MultipartWriter() as writer:
writer.append('test')
writer.append_json({'passed': True})
writer.append(open('src/main.rs'))
- resp = yield from aiohttp.request(
+ resp = await aiohttp.ClientSession().request(
"post", 'http://localhost:8080/multipart',
data=writer, headers=writer.headers)
print(resp)
diff --git a/examples/multipart/src/main.rs b/examples/multipart/src/main.rs
index a1f31527d..7da6145a9 100644
--- a/examples/multipart/src/main.rs
+++ b/examples/multipart/src/main.rs
@@ -2,76 +2,58 @@
extern crate actix;
extern crate actix_web;
extern crate env_logger;
+extern crate futures;
use actix::*;
use actix_web::*;
-struct MyRoute;
+use futures::{Future, Stream};
+use futures::future::{result, Either};
-impl Actor for MyRoute {
- type Context = HttpContext;
-}
-impl Route for MyRoute {
- type State = ();
+fn index(mut req: HttpRequest) -> Box>
+{
+ println!("{:?}", req);
- fn request(mut req: HttpRequest, ctx: &mut HttpContext) -> RouteResult {
- println!("{:?}", req);
+ req.multipart() // <- get multipart stream for current request
+ .from_err() // <- convert multipart errors
+ .and_then(|item| { // <- iterate over multipart items
+ match item {
+ // Handle multipart Field
+ multipart::MultipartItem::Field(field) => {
+ println!("==== FIELD ==== {:?}", field);
- let multipart = req.multipart()?;
-
- // get Multipart stream
- WrapStream::::actstream(multipart)
- .and_then(|item, act, ctx| {
- // Multipart stream is a stream of Fields and nested Multiparts
- match item {
- multipart::MultipartItem::Field(field) => {
- println!("==== FIELD ==== {:?}", field);
-
- // Read field's stream
- fut::Either::A(
- field.actstream()
- .map(|chunk, act, ctx| {
- println!(
- "-- CHUNK: \n{}",
- std::str::from_utf8(&chunk.0).unwrap());
- })
- .finish())
- },
- multipart::MultipartItem::Nested(mp) => {
- // Do nothing for nested multipart stream
- fut::Either::B(fut::ok(()))
- }
+ // Field in turn is stream of *Bytes* object
+ Either::A(
+ field.map_err(Error::from)
+ .map(|chunk| {
+ println!("-- CHUNK: \n{}",
+ std::str::from_utf8(&chunk).unwrap());})
+ .finish())
+ },
+ multipart::MultipartItem::Nested(mp) => {
+ // Or item could be nested Multipart stream
+ Either::B(result(Ok(())))
}
- })
- // wait until stream finish
- .finish()
- .map_err(|e, act, ctx| {
- ctx.start(httpcodes::HTTPBadRequest);
- ctx.write_eof();
- })
- .map(|_, act, ctx| {
- ctx.start(httpcodes::HTTPOk);
- ctx.write_eof();
- })
- .spawn(ctx);
-
- Reply::async(MyRoute)
- }
+ }
+ })
+ .finish() // <- Stream::finish() combinator from actix
+ .map(|_| httpcodes::HTTPOk.into())
+ .responder()
}
fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("multipart-example");
- HttpServer::new(
- vec![
- Application::default("/")
- .resource("/multipart", |r| {
- r.post::();
- }).finish()
- ])
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
+ let addr = HttpServer::new(
+ || Application::new()
+ .middleware(middleware::Logger::default()) // <- logger
+ .resource("/multipart", |r| r.method(Method::POST).a(index)))
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
+ println!("Starting http server: 127.0.0.1:8080");
let _ = sys.run();
}
diff --git a/examples/state/Cargo.toml b/examples/state/Cargo.toml
new file mode 100644
index 000000000..149e8128e
--- /dev/null
+++ b/examples/state/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "state"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+futures = "*"
+env_logger = "0.4"
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
\ No newline at end of file
diff --git a/examples/state/README.md b/examples/state/README.md
new file mode 100644
index 000000000..127ed2a0f
--- /dev/null
+++ b/examples/state/README.md
@@ -0,0 +1,15 @@
+# state
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/state
+cargo run
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+- [http://localhost:8080/](http://localhost:8080/)
diff --git a/examples/state.rs b/examples/state/src/main.rs
similarity index 80%
rename from examples/state.rs
rename to examples/state/src/main.rs
index 52a2da799..395007aed 100644
--- a/examples/state.rs
+++ b/examples/state/src/main.rs
@@ -7,10 +7,12 @@ extern crate actix;
extern crate actix_web;
extern crate env_logger;
-use actix::*;
-use actix_web::*;
use std::cell::Cell;
+use actix::*;
+use actix_web::*;
+
+/// Application state
struct AppState {
counter: Cell,
}
@@ -34,11 +36,10 @@ impl Actor for MyWebSocket {
type Context = HttpContext;
}
-impl StreamHandler for MyWebSocket {}
impl Handler for MyWebSocket {
- fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context)
- -> Response
- {
+ type Result = ();
+
+ fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
self.counter += 1;
println!("WS({}): {:?}", self.counter, msg);
match msg {
@@ -50,7 +51,6 @@ impl Handler for MyWebSocket {
}
_ => (),
}
- Self::empty()
}
}
@@ -59,15 +59,18 @@ fn main() {
let _ = env_logger::init();
let sys = actix::System::new("ws-example");
- HttpServer::new(
- Application::build("/", AppState{counter: Cell::new(0)})
+ let addr = HttpServer::new(
+ || Application::with_state(AppState{counter: Cell::new(0)})
// enable logger
- .middleware(middlewares::Logger::default())
+ .middleware(middleware::Logger::default())
// websocket route
- .resource("/ws/", |r| r.get(|r| ws::start(r, MyWebSocket{counter: 0})))
+ .resource(
+ "/ws/", |r|
+ r.method(Method::GET).f(|req| ws::start(req, MyWebSocket{counter: 0})))
// register simple handler, handle all methods
- .handler("/", index))
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
+ .resource("/", |r| r.f(index)))
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
diff --git a/examples/static/actixLogo.png b/examples/static/actixLogo.png
new file mode 100644
index 000000000..142e4e8d5
Binary files /dev/null and b/examples/static/actixLogo.png differ
diff --git a/examples/static/favicon.ico b/examples/static/favicon.ico
new file mode 100644
index 000000000..03018db5b
Binary files /dev/null and b/examples/static/favicon.ico differ
diff --git a/examples/template_tera/Cargo.toml b/examples/template_tera/Cargo.toml
new file mode 100644
index 000000000..3862fb803
--- /dev/null
+++ b/examples/template_tera/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "template-tera"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+workspace = "../.."
+
+[dependencies]
+env_logger = "0.4"
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web" }
+tera = "*"
diff --git a/examples/template_tera/README.md b/examples/template_tera/README.md
new file mode 100644
index 000000000..35829599f
--- /dev/null
+++ b/examples/template_tera/README.md
@@ -0,0 +1,17 @@
+# template_tera
+
+Minimal example of using the template [tera](https://github.com/Keats/tera) that displays a form.
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/template_tera
+cargo run (or ``cargo watch -x run``)
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+- [http://localhost:8080](http://localhost:8080)
diff --git a/examples/template_tera/src/main.rs b/examples/template_tera/src/main.rs
new file mode 100644
index 000000000..17a14c70c
--- /dev/null
+++ b/examples/template_tera/src/main.rs
@@ -0,0 +1,47 @@
+extern crate actix;
+extern crate actix_web;
+extern crate env_logger;
+#[macro_use]
+extern crate tera;
+
+use actix_web::*;
+
+
+struct State {
+ template: tera::Tera, // <- store tera template in application state
+}
+
+fn index(req: HttpRequest) -> Result {
+ let s = if let Some(name) = req.query().get("name") { // <- submitted form
+ let mut ctx = tera::Context::new();
+ ctx.add("name", &name.to_owned());
+ ctx.add("text", &"Welcome!".to_owned());
+ req.state().template.render("user.html", &ctx)
+ .map_err(|_| error::ErrorInternalServerError("Template error"))?
+ } else {
+ req.state().template.render("index.html", &tera::Context::new())
+ .map_err(|_| error::ErrorInternalServerError("Template error"))?
+ };
+ Ok(httpcodes::HTTPOk.build()
+ .content_type("text/html")
+ .body(s)?)
+}
+
+fn main() {
+ ::std::env::set_var("RUST_LOG", "actix_web=info");
+ let _ = env_logger::init();
+ let sys = actix::System::new("tera-example");
+
+ let addr = HttpServer::new(|| {
+ let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
+
+ Application::with_state(State{template: tera})
+ // enable logger
+ .middleware(middleware::Logger::default())
+ .resource("/", |r| r.method(Method::GET).f(index))})
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
+
+ println!("Started http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
diff --git a/examples/template_tera/templates/index.html b/examples/template_tera/templates/index.html
new file mode 100644
index 000000000..d8a47bc09
--- /dev/null
+++ b/examples/template_tera/templates/index.html
@@ -0,0 +1,17 @@
+
+
+
+
+ Actix web
+
+
+ Welcome!
+
+
What is your name?
+
+
+
+
diff --git a/examples/template_tera/templates/user.html b/examples/template_tera/templates/user.html
new file mode 100644
index 000000000..cb5328915
--- /dev/null
+++ b/examples/template_tera/templates/user.html
@@ -0,0 +1,13 @@
+
+
+
+
+ Actix web
+
+
+ Hi, {{ name }}!
+
+ {{ text }}
+
+
+
diff --git a/examples/tls/Cargo.toml b/examples/tls/Cargo.toml
index fbb22fb77..e6d39742d 100644
--- a/examples/tls/Cargo.toml
+++ b/examples/tls/Cargo.toml
@@ -2,6 +2,7 @@
name = "tls-example"
version = "0.1.0"
authors = ["Nikolay Kim "]
+workspace = "../.."
[[bin]]
name = "server"
@@ -9,5 +10,5 @@ path = "src/main.rs"
[dependencies]
env_logger = "0.4"
-actix = "^0.3.1"
-actix-web = { git = "https://github.com/actix/actix-web.git", features=["alpn"] }
+actix = "0.4"
+actix-web = { git = "https://github.com/actix/actix-web", features=["alpn"] }
diff --git a/examples/tls/README.md b/examples/tls/README.md
index bd1f2400d..1bc9ba3b7 100644
--- a/examples/tls/README.md
+++ b/examples/tls/README.md
@@ -1,5 +1,16 @@
# tls example
-To start server use command: `cargo run`
+## Usage
-Test command: `curl -v https://127.0.0.1:8080/index.html --compress -k`
+### server
+
+```bash
+cd actix-web/examples/tls
+cargo run (or ``cargo watch -x run``)
+# Started http server: 127.0.0.1:8443
+```
+
+### web client
+
+- curl: ``curl -v https://127.0.0.1:8443/index.html --compress -k``
+- browser: [https://127.0.0.1:8443/index.html](https://127.0.0.1:8080/index.html)
diff --git a/examples/tls/src/main.rs b/examples/tls/src/main.rs
index 81574e5e5..15cfcc666 100644
--- a/examples/tls/src/main.rs
+++ b/examples/tls/src/main.rs
@@ -8,6 +8,7 @@ use std::io::Read;
use actix_web::*;
+
/// somple handle
fn index(req: HttpRequest) -> Result {
println!("{:?}", req);
@@ -29,21 +30,22 @@ fn main() {
file.read_to_end(&mut pkcs12).unwrap();
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
- HttpServer::new(
- Application::default("/")
+ let addr = HttpServer::new(
+ || Application::new()
// enable logger
- .middleware(middlewares::Logger::default())
+ .middleware(middleware::Logger::default())
// register simple handler, handle all methods
- .handler("/index.html", index)
+ .resource("/index.html", |r| r.f(index))
// with path parameters
- .resource("/", |r| r.handler(Method::GET, |req| {
+ .resource("/", |r| r.method(Method::GET).f(|req| {
httpcodes::HTTPFound
.build()
.header("LOCATION", "/index.html")
.body(Body::Empty)
})))
- .serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
+ .bind("127.0.0.1:8443").unwrap()
+ .start_ssl(&pkcs12).unwrap();
- println!("Started http server: 127.0.0.1:8080");
+ println!("Started http server: 127.0.0.1:8443");
let _ = sys.run();
}
diff --git a/examples/websocket-chat/Cargo.toml b/examples/websocket-chat/Cargo.toml
index 2a5c92925..a155e0e11 100644
--- a/examples/websocket-chat/Cargo.toml
+++ b/examples/websocket-chat/Cargo.toml
@@ -2,6 +2,7 @@
name = "websocket-example"
version = "0.1.0"
authors = ["Nikolay Kim "]
+workspace = "../.."
[[bin]]
name = "server"
@@ -24,5 +25,6 @@ serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"
-actix = "^0.3.1"
-actix-web = { git = "https://github.com/actix/actix-web.git" }
+#actix = "0.4"
+actix = { git = "https://github.com/actix/actix" }
+actix-web = { git = "https://github.com/actix/actix-web" }
diff --git a/examples/websocket-chat/README.md b/examples/websocket-chat/README.md
index 2e75343b1..28d734dd3 100644
--- a/examples/websocket-chat/README.md
+++ b/examples/websocket-chat/README.md
@@ -1,6 +1,6 @@
# Websocket chat example
-This is extension of the
+This is extension of the
[actix chat example](https://github.com/actix/actix/tree/master/examples/chat)
Added features:
@@ -9,18 +9,16 @@ Added features:
* Chat server runs in separate thread
* Tcp listener runs in separate thread
-
## Server
Chat server listens for incoming tcp connections. Server can access several types of message:
- * `\list` - list all available rooms
- * `\join name` - join room, if room does not exist, create new one
- * `\name name` - set session name
- * `some message` - just string, send messsage to all peers in same room
- * client has to send heartbeat `Ping` messages, if server does not receive a heartbeat
- message for 10 seconds connection gets droppped
-
+* `\list` - list all available rooms
+* `\join name` - join room, if room does not exist, create new one
+* `\name name` - set session name
+* `some message` - just string, send messsage to all peers in same room
+* client has to send heartbeat `Ping` messages, if server does not receive a heartbeat message for 10 seconds connection gets droppped
+
To start server use command: `cargo run --bin server`
## Client
@@ -29,7 +27,6 @@ Client connects to server. Reads input from stdin and sends to server.
To run client use command: `cargo run --bin client`
-
## WebSocket Browser Client
-Open url: http://localhost:8080/
+Open url: [http://localhost:8080/](http://localhost:8080/)
diff --git a/examples/websocket-chat/src/client.rs b/examples/websocket-chat/src/client.rs
index c46a4875c..c57825fc9 100644
--- a/examples/websocket-chat/src/client.rs
+++ b/examples/websocket-chat/src/client.rs
@@ -1,4 +1,4 @@
-extern crate actix;
+#[macro_use] extern crate actix;
extern crate bytes;
extern crate byteorder;
extern crate futures;
@@ -56,13 +56,9 @@ fn main() {
struct ChatClient;
+#[derive(Message)]
struct ClientCommand(String);
-impl ResponseType for ClientCommand {
- type Item = ();
- type Error = ();
-}
-
impl Actor for ChatClient {
type Context = FramedContext;
@@ -70,6 +66,15 @@ impl Actor for ChatClient {
// start heartbeats otherwise server will disconnect after 10 seconds
self.hb(ctx)
}
+
+ fn stopping(&mut self, _: &mut FramedContext) -> bool {
+ println!("Disconnected");
+
+ // Stop application on disconnect
+ Arbiter::system().send(actix::msgs::SystemExit(0));
+
+ true
+ }
}
impl ChatClient {
@@ -83,14 +88,13 @@ impl ChatClient {
}
/// Handle stdin commands
-impl Handler for ChatClient
-{
- fn handle(&mut self, msg: ClientCommand, ctx: &mut FramedContext)
- -> Response
- {
+impl Handler for ChatClient {
+ type Result = ();
+
+ fn handle(&mut self, msg: ClientCommand, ctx: &mut FramedContext) {
let m = msg.0.trim();
if m.is_empty() {
- return Self::empty()
+ return
}
// we check for /sss type of messages
@@ -112,8 +116,6 @@ impl Handler for ChatClient
} else {
let _ = ctx.send(codec::ChatRequest::Message(m.to_owned()));
}
-
- Self::empty()
}
}
@@ -122,40 +124,26 @@ impl Handler for ChatClient
impl FramedActor for ChatClient {
type Io = TcpStream;
type Codec = codec::ClientChatCodec;
-}
-impl StreamHandler for ChatClient {
-
- fn finished(&mut self, _: &mut FramedContext) {
- println!("Disconnected");
-
- // Stop application on disconnect
- Arbiter::system().send(msgs::SystemExit(0));
- }
-}
-
-impl Handler for ChatClient {
-
- fn handle(&mut self, msg: codec::ChatResponse, _: &mut FramedContext)
- -> Response
- {
+ fn handle(&mut self, msg: io::Result, ctx: &mut FramedContext) {
match msg {
- codec::ChatResponse::Message(ref msg) => {
- println!("message: {}", msg);
- }
- codec::ChatResponse::Joined(ref msg) => {
- println!("!!! joined: {}", msg);
- }
- codec::ChatResponse::Rooms(rooms) => {
- println!("\n!!! Available rooms:");
- for room in rooms {
- println!("{}", room);
+ Err(_) => ctx.stop(),
+ Ok(msg) => match msg {
+ codec::ChatResponse::Message(ref msg) => {
+ println!("message: {}", msg);
}
- println!("");
+ codec::ChatResponse::Joined(ref msg) => {
+ println!("!!! joined: {}", msg);
+ }
+ codec::ChatResponse::Rooms(rooms) => {
+ println!("\n!!! Available rooms:");
+ for room in rooms {
+ println!("{}", room);
+ }
+ println!("");
+ }
+ _ => (),
}
- _ => (),
}
-
- Self::empty()
}
}
diff --git a/examples/websocket-chat/src/main.rs b/examples/websocket-chat/src/main.rs
index ae123d5ee..aec05ec74 100644
--- a/examples/websocket-chat/src/main.rs
+++ b/examples/websocket-chat/src/main.rs
@@ -10,6 +10,7 @@ extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
+#[macro_use]
extern crate actix;
extern crate actix_web;
@@ -29,7 +30,7 @@ struct WsChatSessionState {
}
/// Entry point for our route
-fn chat_route(req: HttpRequest) -> Result {
+fn chat_route(req: HttpRequest) -> Result {
ws::start(
req,
WsChatSession {
@@ -52,23 +53,49 @@ struct WsChatSession {
impl Actor for WsChatSession {
type Context = HttpContext;
+
+ /// Method is called on actor start.
+ /// We register ws session with ChatServer
+ fn started(&mut self, ctx: &mut Self::Context) {
+ // register self in chat server. `AsyncContext::wait` register
+ // future within context, but context waits until this future resolves
+ // before processing any other events.
+ // HttpContext::state() is instance of WsChatSessionState, state is shared across all
+ // routes within application
+ let subs = ctx.sync_subscriber();
+ ctx.state().addr.call(
+ self, server::Connect{addr: subs}).then(
+ |res, act, ctx| {
+ match res {
+ Ok(Ok(res)) => act.id = res,
+ // something is wrong with chat server
+ _ => ctx.stop(),
+ }
+ fut::ok(())
+ }).wait(ctx);
+ }
+
+ fn stopping(&mut self, ctx: &mut Self::Context) -> bool {
+ // notify chat server
+ ctx.state().addr.send(server::Disconnect{id: self.id});
+ true
+ }
}
/// Handle messages from chat server, we simply send it to peer websocket
impl Handler for WsChatSession {
- fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context)
- -> Response
- {
+ type Result = ();
+
+ fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context) {
ws::WsWriter::text(ctx, &msg.0);
- Self::empty()
}
}
/// WebSocket message handler
impl Handler for WsChatSession {
- fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context)
- -> Response
- {
+ type Result = ();
+
+ fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Ping(msg) =>
@@ -140,42 +167,9 @@ impl Handler for WsChatSession {
}
_ => (),
}
- Self::empty()
}
}
-impl StreamHandler for WsChatSession
-{
- /// Method is called when stream get polled first time.
- /// We register ws session with ChatServer
- fn started(&mut self, ctx: &mut Self::Context) {
- // register self in chat server. `AsyncContext::wait` register
- // future within context, but context waits until this future resolves
- // before processing any other events.
- // HttpContext::state() is instance of WsChatSessionState, state is shared across all
- // routes within application
- let subs = ctx.sync_subscriber();
- ctx.state().addr.call(
- self, server::Connect{addr: subs}).then(
- |res, act, ctx| {
- match res {
- Ok(Ok(res)) => act.id = res,
- // something is wrong with chat server
- _ => ctx.stop(),
- }
- fut::ok(())
- }).wait(ctx);
- }
-
- /// Method is called when stream finishes, even if stream finishes with error.
- fn finished(&mut self, ctx: &mut Self::Context) {
- // notify chat server
- ctx.state().addr.send(server::Disconnect{id: self.id});
- ctx.stop()
- }
-}
-
-
fn main() {
let _ = env_logger::init();
let sys = actix::System::new("websocket-example");
@@ -192,24 +186,28 @@ fn main() {
Ok(())
}));
- // Websocket sessions state
- let state = WsChatSessionState { addr: server };
-
// Create Http server with websocket support
- HttpServer::new(
- Application::build("/", state)
- // redirect to websocket.html
- .resource("/", |r| r.handler(Method::GET, |req| {
- httpcodes::HTTPFound
- .build()
- .header("LOCATION", "/static/websocket.html")
- .body(Body::Empty)
- }))
- // websocket
- .resource("/ws/", |r| r.get(chat_route))
- // static resources
- .route("/static", StaticFiles::new("static/", true)))
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
+ let addr = HttpServer::new(
+ move || {
+ // Websocket sessions state
+ let state = WsChatSessionState { addr: server.clone() };
+ Application::with_state(state)
+ // redirect to websocket.html
+ .resource("/", |r| r.method(Method::GET).f(|_| {
+ httpcodes::HTTPFound
+ .build()
+ .header("LOCATION", "/static/websocket.html")
+ .finish()
+ }))
+ // websocket
+ .resource("/ws/", |r| r.route().f(chat_route))
+ // static resources
+ .handler("/static/", fs::StaticFiles::new("static/", true))
+ })
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
+
+ println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}
diff --git a/examples/websocket-chat/src/server.rs b/examples/websocket-chat/src/server.rs
index c15644a6a..4eae86d00 100644
--- a/examples/websocket-chat/src/server.rs
+++ b/examples/websocket-chat/src/server.rs
@@ -13,7 +13,7 @@ use session;
/// New chat session is created
pub struct Connect {
- pub addr: Box + Send>,
+ pub addr: Box + Send>,
}
/// Response type for Connect message
@@ -25,16 +25,13 @@ impl ResponseType for Connect {
}
/// Session is disconnected
+#[derive(Message)]
pub struct Disconnect {
pub id: usize,
}
-impl ResponseType for Disconnect {
- type Item = ();
- type Error = ();
-}
-
/// Send message to specific room
+#[derive(Message)]
pub struct Message {
/// Id of the client session
pub id: usize,
@@ -44,11 +41,6 @@ pub struct Message {
pub room: String,
}
-impl ResponseType for Message {
- type Item = ();
- type Error = ();
-}
-
/// List of available rooms
pub struct ListRooms;
@@ -58,6 +50,7 @@ impl ResponseType for ListRooms {
}
/// Join room, if room does not exists create new one.
+#[derive(Message)]
pub struct Join {
/// Client id
pub id: usize,
@@ -65,15 +58,10 @@ pub struct Join {
pub name: String,
}
-impl ResponseType for Join {
- type Item = ();
- type Error = ();
-}
-
/// `ChatServer` manages chat rooms and responsible for coordinating chat session.
/// implementation is super primitive
pub struct ChatServer {
- sessions: HashMap + Send>>,
+ sessions: HashMap + Send>>,
rooms: HashMap>,
rng: RefCell,
}
@@ -118,8 +106,9 @@ impl Actor for ChatServer {
///
/// Register new session and assign unique id to this session
impl Handler for ChatServer {
+ type Result = MessageResult;
- fn handle(&mut self, msg: Connect, _: &mut Context) -> Response {
+ fn handle(&mut self, msg: Connect, _: &mut Context) -> Self::Result {
println!("Someone joined");
// notify all users in same room
@@ -133,14 +122,15 @@ impl Handler for ChatServer {
self.rooms.get_mut(&"Main".to_owned()).unwrap().insert(id);
// send id back
- Self::reply(id)
+ Ok(id)
}
}
/// Handler for Disconnect message.
impl Handler for ChatServer {
+ type Result = ();
- fn handle(&mut self, msg: Disconnect, _: &mut Context) -> Response {
+ fn handle(&mut self, msg: Disconnect, _: &mut Context) {
println!("Someone disconnected");
let mut rooms: Vec = Vec::new();
@@ -158,40 +148,39 @@ impl Handler for ChatServer {
for room in rooms {
self.send_message(&room, "Someone disconnected", 0);
}
-
- Self::empty()
}
}
/// Handler for Message message.
impl Handler for ChatServer {
+ type Result = ();
- fn handle(&mut self, msg: Message, _: &mut Context) -> Response {
+ fn handle(&mut self, msg: Message, _: &mut Context) {
self.send_message(&msg.room, msg.msg.as_str(), msg.id);
-
- Self::empty()
}
}
/// Handler for `ListRooms` message.
impl Handler for ChatServer {
+ type Result = MessageResult;
- fn handle(&mut self, _: ListRooms, _: &mut Context) -> Response {
+ fn handle(&mut self, _: ListRooms, _: &mut Context) -> Self::Result {
let mut rooms = Vec::new();
for key in self.rooms.keys() {
rooms.push(key.to_owned())
}
- Self::reply(rooms)
+ Ok(rooms)
}
}
/// Join room, send disconnect message to old room
/// send join message to new room
impl Handler for ChatServer {
+ type Result = ();
- fn handle(&mut self, msg: Join, _: &mut Context) -> Response {
+ fn handle(&mut self, msg: Join, _: &mut Context) {
let Join {id, name} = msg;
let mut rooms = Vec::new();
@@ -211,7 +200,5 @@ impl Handler for ChatServer {
}
self.send_message(&name, "Someone connected", id);
self.rooms.get_mut(&name).unwrap().insert(id);
-
- Self::empty()
}
}
diff --git a/examples/websocket-chat/src/session.rs b/examples/websocket-chat/src/session.rs
index 961955a59..b0725fde4 100644
--- a/examples/websocket-chat/src/session.rs
+++ b/examples/websocket-chat/src/session.rs
@@ -6,20 +6,16 @@ use std::time::{Instant, Duration};
use futures::Stream;
use tokio_core::net::{TcpStream, TcpListener};
-use actix::*;
+use actix::prelude::*;
use server::{self, ChatServer};
use codec::{ChatRequest, ChatResponse, ChatCodec};
/// Chat server sends this messages to session
+#[derive(Message)]
pub struct Message(pub String);
-impl ResponseType for Message {
- type Item = ();
- type Error = ();
-}
-
/// `ChatSession` actor is responsible for tcp peer communitions.
pub struct ChatSession {
/// unique session id
@@ -36,104 +32,87 @@ impl Actor for ChatSession {
/// For tcp communication we are going to use `FramedContext`.
/// It is convinient wrapper around `Framed` object from `tokio_io`
type Context = FramedContext;
-}
-/// To use `FramedContext` we have to define Io type and Codec
-impl FramedActor for ChatSession {
- type Io = TcpStream;
- type Codec= ChatCodec;
-}
-
-/// Also `FramedContext` requires Actor which is able to handle stream
-/// of `::Item` items.
-impl StreamHandler for ChatSession {
-
- fn started(&mut self, ctx: &mut FramedContext) {
+ fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
- self.addr.call(self, server::Connect{addr: ctx.sync_subscriber()}).then(|res, act, ctx| {
- match res {
- Ok(Ok(res)) => act.id = res,
- // something is wrong with chat server
- _ => ctx.stop(),
- }
- fut::ok(())
- }).wait(ctx);
+ let addr: SyncAddress<_> = ctx.address();
+ self.addr.call(self, server::Connect{addr: addr.subscriber()})
+ .then(|res, act, ctx| {
+ match res {
+ Ok(Ok(res)) => act.id = res,
+ // something is wrong with chat server
+ _ => ctx.stop(),
+ }
+ actix::fut::ok(())
+ }).wait(ctx);
}
- fn finished(&mut self, ctx: &mut FramedContext) {
+ fn stopping(&mut self, ctx: &mut Self::Context) -> bool {
// notify chat server
self.addr.send(server::Disconnect{id: self.id});
-
- ctx.stop()
+ true
}
}
-impl Handler for ChatSession {
-
- /// We'll stop chat session actor on any error, high likely it is just
- /// termination of the tcp stream.
- fn error(&mut self, _: io::Error, ctx: &mut FramedContext) {
- ctx.stop()
- }
+/// To use `FramedContext` we have to define Io type and Codec
+impl FramedActor for ChatSession {
+ type Io = TcpStream;
+ type Codec= ChatCodec;
/// This is main event loop for client requests
- fn handle(&mut self, msg: ChatRequest, ctx: &mut FramedContext)
- -> Response
- {
+ fn handle(&mut self, msg: io::Result, ctx: &mut FramedContext) {
match msg {
- ChatRequest::List => {
- // Send ListRooms message to chat server and wait for response
- println!("List rooms");
- self.addr.call(self, server::ListRooms).then(|res, _, ctx| {
- match res {
- Ok(Ok(rooms)) => {
- let _ = ctx.send(ChatResponse::Rooms(rooms));
- },
+ Err(_) => ctx.stop(),
+ Ok(msg) => match msg {
+ ChatRequest::List => {
+ // Send ListRooms message to chat server and wait for response
+ println!("List rooms");
+ self.addr.call(self, server::ListRooms).then(|res, _, ctx| {
+ match res {
+ Ok(Ok(rooms)) => {
+ let _ = ctx.send(ChatResponse::Rooms(rooms));
+ },
_ => println!("Something is wrong"),
- }
- fut::ok(())
- }).wait(ctx)
- // .wait(ctx) pauses all events in context,
- // so actor wont receive any new messages until it get list of rooms back
- },
- ChatRequest::Join(name) => {
- println!("Join to room: {}", name);
- self.room = name.clone();
- self.addr.send(server::Join{id: self.id, name: name.clone()});
- let _ = ctx.send(ChatResponse::Joined(name));
- },
- ChatRequest::Message(message) => {
- // send message to chat server
- println!("Peer message: {}", message);
- self.addr.send(
- server::Message{id: self.id,
- msg: message, room:
- self.room.clone()})
+ }
+ actix::fut::ok(())
+ }).wait(ctx)
+ // .wait(ctx) pauses all events in context,
+ // so actor wont receive any new messages until it get list of rooms back
+ },
+ ChatRequest::Join(name) => {
+ println!("Join to room: {}", name);
+ self.room = name.clone();
+ self.addr.send(server::Join{id: self.id, name: name.clone()});
+ let _ = ctx.send(ChatResponse::Joined(name));
+ },
+ ChatRequest::Message(message) => {
+ // send message to chat server
+ println!("Peer message: {}", message);
+ self.addr.send(
+ server::Message{id: self.id,
+ msg: message, room:
+ self.room.clone()})
+ }
+ // we update heartbeat time on ping from peer
+ ChatRequest::Ping =>
+ self.hb = Instant::now(),
}
- // we update heartbeat time on ping from peer
- ChatRequest::Ping =>
- self.hb = Instant::now(),
}
-
- Self::empty()
}
}
/// Handler for Message, chat server sends this message, we just send string to peer
impl Handler for ChatSession {
+ type Result = ();
- fn handle(&mut self, msg: Message, ctx: &mut FramedContext)
- -> Response
- {
+ fn handle(&mut self, msg: Message, ctx: &mut FramedContext) {
// send message to peer
let _ = ctx.send(ChatResponse::Message(msg.0));
-
- Self::empty()
}
}
@@ -188,7 +167,9 @@ impl TcpServer {
// So to be able to handle this events `Server` actor has to implement
// stream handler `StreamHandler<(TcpStream, net::SocketAddr), io::Error>`
let _: () = TcpServer::create(|ctx| {
- ctx.add_stream(listener.incoming().map(|(t, a)| TcpConnect(t, a)));
+ ctx.add_message_stream(listener.incoming()
+ .map_err(|_| ())
+ .map(|(t, a)| TcpConnect(t, a)));
TcpServer{chat: chat}
});
}
@@ -200,27 +181,17 @@ impl Actor for TcpServer {
type Context = Context;
}
+#[derive(Message)]
struct TcpConnect(TcpStream, net::SocketAddr);
-impl ResponseType for TcpConnect {
- type Item = ();
- type Error = ();
-}
-
/// Handle stream of TcpStream's
-impl StreamHandler for TcpServer {}
+impl Handler for TcpServer {
+ type Result = ();
-impl Handler for TcpServer {
-
- fn handle(&mut self, msg: TcpConnect, _: &mut Context) -> Response
- {
+ fn handle(&mut self, msg: TcpConnect, _: &mut Context) {
// For each incoming connection we create `ChatSession` actor
// with out chat server address.
let server = self.chat.clone();
let _: () = ChatSession::new(server).framed(msg.0, ChatCodec);
-
- // this is response for message, which is defined by `ResponseType` trait
- // in this case we just return unit.
- Self::empty()
}
}
diff --git a/examples/websocket/Cargo.toml b/examples/websocket/Cargo.toml
new file mode 100644
index 000000000..e75f5c390
--- /dev/null
+++ b/examples/websocket/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "websocket"
+version = "0.1.0"
+authors = ["Nikolay Kim "]
+
+[[bin]]
+name = "server"
+path = "src/main.rs"
+
+[dependencies]
+env_logger = "*"
+futures = "0.1"
+#actix = "0.4"
+actix = { git = "https://github.com/actix/actix.git" }
+actix-web = { git = "https://github.com/actix/actix-web.git" }
diff --git a/examples/websocket/README.md b/examples/websocket/README.md
new file mode 100644
index 000000000..374e939ac
--- /dev/null
+++ b/examples/websocket/README.md
@@ -0,0 +1,27 @@
+# websockect
+
+Simple echo websocket server.
+
+## Usage
+
+### server
+
+```bash
+cd actix-web/examples/websocket
+cargo run
+# Started http server: 127.0.0.1:8080
+```
+
+### web client
+
+- [http://localhost:8080/ws/index.html](http://localhost:8080/ws/index.html)
+
+### python client
+
+- ``pip install aiohttp``
+- ``python websocket-client.py``
+
+if ubuntu :
+
+- ``pip3 install aiohttp``
+- ``python3 websocket-client.py``
diff --git a/examples/websocket.rs b/examples/websocket/src/main.rs
similarity index 66%
rename from examples/websocket.rs
rename to examples/websocket/src/main.rs
index 24a88d03b..fea8929de 100644
--- a/examples/websocket.rs
+++ b/examples/websocket/src/main.rs
@@ -11,10 +11,9 @@ extern crate env_logger;
use actix::*;
use actix_web::*;
-
/// do websocket handshake and start `MyWebSocket` actor
-fn ws_index(r: HttpRequest) -> Reply {
- ws::start(r, MyWebSocket).into()
+fn ws_index(r: HttpRequest) -> Result {
+ ws::start(r, MyWebSocket)
}
/// websocket connection is long running connection, it easier
@@ -25,21 +24,11 @@ impl Actor for MyWebSocket {
type Context = HttpContext;
}
-/// Standard actix's stream handler for a stream of `ws::Message`
-impl StreamHandler for MyWebSocket {
- fn started(&mut self, ctx: &mut Self::Context) {
- println!("WebSocket session openned");
- }
-
- fn finished(&mut self, ctx: &mut Self::Context) {
- println!("WebSocket session closed");
- }
-}
-
+/// Handler for `ws::Message`
impl Handler for MyWebSocket {
- fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext)
- -> Response
- {
+ type Result = ();
+
+ fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext) {
// process websocket messages
println!("WS: {:?}", msg);
match msg {
@@ -51,7 +40,6 @@ impl Handler for MyWebSocket {
}
_ => (),
}
- Self::empty()
}
}
@@ -60,16 +48,17 @@ fn main() {
let _ = env_logger::init();
let sys = actix::System::new("ws-example");
- HttpServer::new(
- Application::default("/")
+ let _addr = HttpServer::new(
+ || Application::new()
// enable logger
- .middleware(middlewares::Logger::default())
+ .middleware(middleware::Logger::default())
// websocket route
- .resource("/ws/", |r| r.get(ws_index))
+ .resource("/ws/", |r| r.method(Method::GET).f(ws_index))
// static files
- .route("/", StaticFiles::new("examples/static/", true)))
+ .handler("/", fs::StaticFiles::new("../static/", true)))
// start http server on 127.0.0.1:8080
- .serve::<_, ()>("127.0.0.1:8080").unwrap();
+ .bind("127.0.0.1:8080").unwrap()
+ .start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
diff --git a/examples/websocket-client.py b/examples/websocket/websocket-client.py
similarity index 100%
rename from examples/websocket-client.py
rename to examples/websocket/websocket-client.py
diff --git a/guide/src/SUMMARY.md b/guide/src/SUMMARY.md
index 93a265a42..d76840f9c 100644
--- a/guide/src/SUMMARY.md
+++ b/guide/src/SUMMARY.md
@@ -3,13 +3,14 @@
[Quickstart](./qs_1.md)
- [Getting Started](./qs_2.md)
- [Application](./qs_3.md)
+- [Server](./qs_3_5.md)
- [Handler](./qs_4.md)
-- [Resources and Routes](./qs_5.md)
-- [Application state](./qs_6.md)
-- [Request](./qs_7.md)
-- [Response](./qs_8.md)
-- [WebSockets](./qs_9.md)
-- [User sessions](./qs_10.md)
-- [Logging](./qs_11.md)
+- [Errors](./qs_4_5.md)
+- [URL Dispatch](./qs_5.md)
+- [Request & Response](./qs_7.md)
+- [Testing](./qs_8.md)
+- [Middlewares](./qs_10.md)
- [Static file handling](./qs_12.md)
+- [WebSockets](./qs_9.md)
- [HTTP/2](./qs_13.md)
+- [Database integration](./qs_14.md)
diff --git a/guide/src/qs_1.md b/guide/src/qs_1.md
index 09e83b586..8d2ee83c2 100644
--- a/guide/src/qs_1.md
+++ b/guide/src/qs_1.md
@@ -1,6 +1,6 @@
-# Quickstart
+# Quick start
-Before you can start writing a actix web application, you’ll need a version of Rust installed.
+Before you can start writing a actix web application, you’ll need a version of Rust installed.
We recommend you use rustup to install or configure such a version.
## Install Rust
@@ -23,12 +23,12 @@ Actix web framework requies rust version 1.20 and up.
The fastest way to start experimenting with actix web is to clone the actix web repository
and run the included examples in the examples/ directory. The following set of
-commands runs the `basic` example:
+commands runs the `basics` example:
```bash
git clone https://github.com/actix/actix-web
-cd actix-web
-cargo run --example basic
+cd actix-web/examples/basics
+cargo run
```
-Check `examples/` directory for more examples.
+Check [examples/](https://github.com/actix/actix-web/tree/master/examples) directory for more examples.
diff --git a/guide/src/qs_10.md b/guide/src/qs_10.md
index 0c28628eb..8974f241d 100644
--- a/guide/src/qs_10.md
+++ b/guide/src/qs_10.md
@@ -1 +1,206 @@
-# User sessions
+# Middlewares
+
+Actix middlewares system allows to add additional behaviour to request/response processing.
+Middleware can hook into incomnig request process and modify request or halt request
+processing and return response early. Also it can hook into response processing.
+
+Typically middlewares involves in following actions:
+
+* Pre-process the Request
+* Post-process a Response
+* Modify application state
+* Access external services (redis, logging, sessions)
+
+Middlewares are registered for each application and get executed in same order as
+registraton order. In general, *middleware* is a type that implements
+[*Middleware trait*](../actix_web/middlewares/trait.Middleware.html). Each method
+in this trait has default implementation. Each method can return result immidietly
+or *future* object.
+
+Here is example of simple middleware that adds request and response headers:
+
+```rust
+# extern crate http;
+# extern crate actix_web;
+use http::{header, HttpTryFrom};
+use actix_web::*;
+use actix_web::middleware::{Middleware, Started, Response};
+
+struct Headers; // <- Our middleware
+
+/// Middleware implementation, middlewares are generic over application state,
+/// so you can access state with `HttpRequest::state()` method.
+impl Middleware for Headers {
+
+ /// Method is called when request is ready. It may return
+ /// future, which should resolve before next middleware get called.
+ fn start(&self, req: &mut HttpRequest) -> Started {
+ req.headers_mut().insert(
+ header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"));
+ Started::Done
+ }
+
+ /// Method is called when handler returns response,
+ /// but before sending http message to peer.
+ fn response(&self, req: &mut HttpRequest, mut resp: HttpResponse) -> Response {
+ resp.headers_mut().insert(
+ header::HeaderName::try_from("X-VERSION").unwrap(),
+ header::HeaderValue::from_static("0.2"));
+ Response::Done(resp)
+ }
+}
+
+fn main() {
+ Application::new()
+ .middleware(Headers) // <- Register middleware, this method could be called multiple times
+ .resource("/", |r| r.h(httpcodes::HTTPOk));
+}
+```
+
+Active provides several useful middlewares, like *logging*, *user sessions*, etc.
+
+
+## Logging
+
+Logging is implemented as middleware.
+It is common to register logging middleware as first middleware for application.
+Logging middleware has to be registered for each application.
+
+### Usage
+
+Create `Logger` middleware with the specified `format`.
+Default `Logger` could be created with `default` method, it uses the default format:
+
+```ignore
+ %a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
+```
+```rust
+# extern crate actix_web;
+use actix_web::Application;
+use actix_web::middleware::Logger;
+
+fn main() {
+ Application::new()
+ .middleware(Logger::default())
+ .middleware(Logger::new("%a %{User-Agent}i"))
+ .finish();
+}
+```
+
+Here is example of default logging format:
+
+```
+INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
+INFO:actix_web::middleware::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0" 0.000646
+```
+
+### Format
+
+ `%%` The percent sign
+
+ `%a` Remote IP-address (IP-address of proxy if using reverse proxy)
+
+ `%t` Time when the request was started to process
+
+ `%P` The process ID of the child that serviced the request
+
+ `%r` First line of request
+
+ `%s` Response status code
+
+ `%b` Size of response in bytes, including HTTP headers
+
+ `%T` Time taken to serve the request, in seconds with floating fraction in .06f format
+
+ `%D` Time taken to serve the request, in milliseconds
+
+ `%{FOO}i` request.headers['FOO']
+
+ `%{FOO}o` response.headers['FOO']
+
+ `%{FOO}e` os.environ['FOO']
+
+
+## Default headers
+
+To set default response headers `DefaultHeaders` middleware could be used.
+*DefaultHeaders* middleware does not set header if response headers already contains
+specified header.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+
+fn main() {
+ let app = Application::new()
+ .middleware(
+ middleware::DefaultHeaders::build()
+ .header("X-Version", "0.2")
+ .finish())
+ .resource("/test", |r| {
+ r.method(Method::GET).f(|req| httpcodes::HTTPOk);
+ r.method(Method::HEAD).f(|req| httpcodes::HTTPMethodNotAllowed);
+ })
+ .finish();
+}
+```
+
+## User sessions
+
+Actix provides general solution for session management.
+[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleare can be
+use with different backend types to store session data in different backends.
+By default only cookie session backend is implemented. Other backend implementations
+could be added later.
+
+[*Cookie session backend*](../actix_web/middleware/struct.CookieSessionBackend.html)
+uses signed cookies as session storage. *Cookie session backend* creates sessions which
+are limited to storing fewer than 4000 bytes of data (as the payload must fit into a
+single cookie). Internal server error get generated if session contains more than 4000 bytes.
+
+You need to pass a random value to the constructor of *CookieSessionBackend*.
+This is private key for cookie session. When this value is changed, all session data is lost.
+Note that whatever you write into your session is visible by the user (but not modifiable).
+
+In general case, you cretate
+[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleware
+and initializes it with specific backend implementation, like *CookieSessionBackend*.
+To access session data
+[*HttpRequest::session()*](../actix_web/middleware/trait.RequestSession.html#tymethod.session)
+method has to be used. This method returns
+[*Session*](../actix_web/middleware/struct.Session.html) object, which allows to get or set
+session data.
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+use actix_web::*;
+use actix_web::middleware::{RequestSession, SessionStorage, CookieSessionBackend};
+
+fn index(mut req: HttpRequest) -> Result<&'static str> {
+ // access session data
+ if let Some(count) = req.session().get::("counter")? {
+ println!("SESSION value: {}", count);
+ req.session().set("counter", count+1)?;
+ } else {
+ req.session().set("counter", 1)?;
+ }
+
+ Ok("Welcome!")
+}
+
+fn main() {
+# let sys = actix::System::new("basic-example");
+ HttpServer::new(
+ || Application::new()
+ .middleware(SessionStorage::new( // <- create session middleware
+ CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend
+ .secure(false)
+ .finish()
+ )))
+ .bind("127.0.0.1:59880").unwrap()
+ .start();
+# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
+# let _ = sys.run();
+}
+```
diff --git a/guide/src/qs_11.md b/guide/src/qs_11.md
deleted file mode 100644
index 5aed847ce..000000000
--- a/guide/src/qs_11.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# Logging
-
-Logging is implemented as middleware. Middlewares get executed in same order as registraton order.
-It is common to register logging middleware as first middleware for application.
-Logging middleware has to be registered for each application.
-
-## Usage
-
-Create `Logger` middlewares with the specified `format`.
-Default `Logger` could be created with `default` method, it uses the default format:
-
-```ignore
- %a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
-```
-```rust
-extern crate actix_web;
-use actix_web::Application;
-use actix_web::middlewares::Logger;
-
-fn main() {
- Application::default("/")
- .middleware(Logger::default())
- .middleware(Logger::new("%a %{User-Agent}i"))
- .finish();
-}
-```
-
-Here is example of default logging format:
-
-```
-INFO:actix_web::middlewares::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
-INFO:actix_web::middlewares::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0" 0.000646
-```
-
-## Format
-
- `%%` The percent sign
-
- `%a` Remote IP-address (IP-address of proxy if using reverse proxy)
-
- `%t` Time when the request was started to process
-
- `%P` The process ID of the child that serviced the request
-
- `%r` First line of request
-
- `%s` Response status code
-
- `%b` Size of response in bytes, including HTTP headers
-
- `%T` Time taken to serve the request, in seconds with floating fraction in .06f format
-
- `%D` Time taken to serve the request, in milliseconds
-
- `%{FOO}i` request.headers['FOO']
-
- `%{FOO}o` response.headers['FOO']
-
- `%{FOO}e` os.environ['FOO']
diff --git a/guide/src/qs_12.md b/guide/src/qs_12.md
index 8220368dd..286709353 100644
--- a/guide/src/qs_12.md
+++ b/guide/src/qs_12.md
@@ -1 +1,44 @@
# Static file handling
+
+## Individual file
+
+It is possible to serve static files with custom path pattern and `NamedFile`. To
+match path tail we can use `[.*]` regex.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+use std::path::PathBuf;
+
+fn index(req: HttpRequest) -> Result {
+ let path: PathBuf = req.match_info().query("tail")?;
+ Ok(fs::NamedFile::open(path)?)
+}
+
+fn main() {
+ Application::new()
+ .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
+ .finish();
+}
+```
+
+## Directory
+
+To serve files from specific directory and sub-directories `StaticFiles` could be used.
+`StaticFiles` must be registered with `Application::handler()` method otherwise
+it won't be able to server sub-paths.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+
+fn main() {
+ Application::new()
+ .handler("/static", fs::StaticFiles::new(".", true))
+ .finish();
+}
+```
+
+First parameter is a base directory. Second parameter is *show_index*, if it is set to *true*
+directory listing would be returned for directories, if it is set to *false*
+then *404 Not Found* would be returned instead of directory listing.
diff --git a/guide/src/qs_13.md b/guide/src/qs_13.md
index 5a2472d4d..193b2e109 100644
--- a/guide/src/qs_13.md
+++ b/guide/src/qs_13.md
@@ -1,10 +1,10 @@
-# HTTP/2
+# HTTP/2.0
-Actix web automatically upgrades connection to `http/2` if possible.
+Actix web automatically upgrades connection to *HTTP/2.0* if possible.
## Negotiation
-`HTTP/2` protocol over tls without prior knowlage requires
+*HTTP/2.0* protocol over tls without prior knowlage requires
[tls alpn](https://tools.ietf.org/html/rfc7301). At the moment only
`rust-openssl` has support. Turn on `alpn` feature to enable `alpn` negotiation.
With enable `alpn` feature `HttpServer` provides
@@ -26,15 +26,16 @@ fn main() {
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
HttpServer::new(
- Application::default("/")
- .handler("/index.html", index)
- .serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
+ || Application::new()
+ .resource("/index.html", |r| r.f(index)))
+ .bind("127.0.0.1:8080").unwrap();
+ .serve_ssl(pkcs12).unwrap();
}
```
-Upgrade to `http/2` schema described in
+Upgrade to *HTTP/2.0* schema described in
[rfc section 3.2](https://http2.github.io/http2-spec/#rfc.section.3.2) is not supported.
-Starting `http/2` with prior knowledge is supported for both clear text connection
+Starting *HTTP/2* with prior knowledge is supported for both clear text connection
and tls connection. [rfc section 3.4](https://http2.github.io/http2-spec/#rfc.section.3.4)
Please check [example](https://github.com/actix/actix-web/tree/master/examples/tls)
diff --git a/guide/src/qs_14.md b/guide/src/qs_14.md
new file mode 100644
index 000000000..26fa4ecfb
--- /dev/null
+++ b/guide/src/qs_14.md
@@ -0,0 +1,124 @@
+# Database integration
+
+## Diesel
+
+At the moment of 1.0 release Diesel does not support asynchronous operations.
+But it possible to use `actix` synchronous actor system as a db interface api.
+Technically sync actors are worker style actors, multiple of them
+can be run in parallel and process messages from same queue (sync actors work in mpmc mode).
+
+Let's create simple db api that can insert new user row into sqlite table.
+We have to define sync actor and connection that this actor will use. Same approach
+could used for other databases.
+
+```rust,ignore
+use actix::prelude::*;*
+
+struct DbExecutor(SqliteConnection);
+
+impl Actor for DbExecutor {
+ type Context = SyncContext;
+}
+```
+
+This is definition of our actor. Now we need to define *create user* message and response.
+
+```rust,ignore
+#[derive(Message)]
+#[rtype(User, Error)]
+struct CreateUser {
+ name: String,
+}
+```
+
+We can send `CreateUser` message to `DbExecutor` actor, and as result we get
+`User` model. Now we need to define actual handler implementation for this message.
+
+```rust,ignore
+impl Handler for DbExecutor {
+
+ fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Response
+ {
+ use self::schema::users::dsl::*;
+
+ // Create insertion model
+ let uuid = format!("{}", uuid::Uuid::new_v4());
+ let new_user = models::NewUser {
+ id: &uuid,
+ name: &msg.name,
+ };
+
+ // normal diesl operations
+ diesel::insert_into(users)
+ .values(&new_user)
+ .execute(&self.0)
+ .expect("Error inserting person");
+
+ let mut items = users
+ .filter(id.eq(&uuid))
+ .load::(&self.0)
+ .expect("Error loading person");
+
+ Self::reply(items.pop().unwrap())
+ }
+}
+```
+
+That is it. Now we can use *DbExecutor* actor from any http handler or middleware.
+All we need is to start *DbExecutor* actors and store address in a state where http handler
+can access it.
+
+```rust,ignore
+/// This is state where we will store *DbExecutor* address.
+struct State {
+ db: SyncAddress,
+}
+
+fn main() {
+ let sys = actix::System::new("diesel-example");
+
+ // Start 3 parallele db executors
+ let addr = SyncArbiter::start(3, || {
+ DbExecutor(SqliteConnection::establish("test.db").unwrap())
+ });
+
+ // Start http server
+ HttpServer::new(move || {
+ Application::with_state(State{db: addr.clone()})
+ .resource("/{name}", |r| r.method(Method::GET).a(index))})
+ .bind("127.0.0.1:8080").unwrap()
+ .start().unwrap();
+
+ println!("Started http server: 127.0.0.1:8080");
+ let _ = sys.run();
+}
+```
+
+And finally we can use address in a requst handler. We get message response
+asynchronously, so handler needs to return future object, also `Route::a()` needs to be
+used for async handler registration.
+
+
+```rust,ignore
+/// Async handler
+fn index(req: HttpRequest) -> Box> {
+ let name = &req.match_info()["name"];
+
+ // Send message to `DbExecutor` actor
+ req.state().db.call_fut(CreateUser{name: name.to_owned()})
+ .from_err()
+ .and_then(|res| {
+ match res {
+ Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?),
+ Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
+ }
+ })
+ .responder()
+}
+```
+
+Full example is available in
+[examples directory](https://github.com/actix/actix-web/tree/master/examples/diesel/).
+
+More information on sync actors could be found in
+[actix documentation](https://docs.rs/actix/0.3.3/actix/sync/index.html).
diff --git a/guide/src/qs_2.md b/guide/src/qs_2.md
index 4fbcf67fa..3c347ce65 100644
--- a/guide/src/qs_2.md
+++ b/guide/src/qs_2.md
@@ -29,29 +29,39 @@ In order to implement a web server, first we need to create a request handler.
A request handler is a function that accepts a `HttpRequest` instance as its only parameter
and returns a type that can be converted into `HttpResponse`:
-```rust,ignore
-extern crate actix_web;
-use actix_web::*;
-
-fn index(req: HttpRequest) -> &'static str {
- "Hello world!"
-}
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+ fn index(req: HttpRequest) -> &'static str {
+ "Hello world!"
+ }
+# fn main() {}
```
Next, create an `Application` instance and register the
request handler with the application's `resource` on a particular *HTTP method* and *path*::
-```rust,ignore
- let app = Application::default("/")
- .resource("/", |r| r.get(index))
- .finish()
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+# fn index(req: HttpRequest) -> &'static str {
+# "Hello world!"
+# }
+# fn main() {
+ Application::new()
+ .resource("/", |r| r.f(index));
+# }
```
After that, application instance can be used with `HttpServer` to listen for incoming
-connections:
+connections. Server accepts function that should return `HttpHandler` instance:
```rust,ignore
- HttpServer::new(app).serve::<_, ()>("127.0.0.1:8088");
+ HttpServer::new(
+ || Application::new()
+ .resource("/", |r| r.f(index)))
+ .bind("127.0.0.1:8088")?
+ .run();
```
That's it. Now, compile and run the program with cargo run.
@@ -59,9 +69,8 @@ Head over to ``http://localhost:8088/`` to see the results.
Here is full source of main.rs file:
-```rust
-extern crate actix;
-extern crate actix_web;
+```rust,ignore
+# extern crate actix_web;
use actix_web::*;
fn index(req: HttpRequest) -> &'static str {
@@ -69,22 +78,15 @@ fn index(req: HttpRequest) -> &'static str {
}
fn main() {
- let sys = actix::System::new("example");
-
HttpServer::new(
- Application::default("/")
- .resource("/", |r| r.get(index)))
- .serve::<_, ()>("127.0.0.1:8088").unwrap();
-
- println!("Started http server: 127.0.0.1:8088");
- // do not copy this line
- actix::Arbiter::system().send(actix::msgs::SystemExit(0));
-
- let _ = sys.run();
+ || Application::new()
+ .resource("/", |r| r.f(index)))
+ .bind("127.0.0.1:8088").expect("Can not bind to 127.0.0.1:8088")
+ .run();
}
```
Note on `actix` crate. Actix web framework is built on top of actix actor library.
`actix::System` initializes actor system, `HttpServer` is an actor and must run within
-proper configured actix system. For more information please check
+properly configured actix system. For more information please check
[actix documentation](https://actix.github.io/actix/actix/)
diff --git a/guide/src/qs_3.md b/guide/src/qs_3.md
index 66606206e..c970b3efe 100644
--- a/guide/src/qs_3.md
+++ b/guide/src/qs_3.md
@@ -5,44 +5,105 @@ It provides routing, middlewares, pre-processing of requests, and post-processin
websocket protcol handling, multipart streams, etc.
All actix web server is built around `Application` instance.
-It is used for registering handlers for routes and resources, middlewares.
-Also it stores applicationspecific state that is shared accross all handlers
+It is used for registering routes for resources, middlewares.
+Also it stores application specific state that is shared across all handlers
within same application.
Application acts as namespace for all routes, i.e all routes for specific application
-has same url path prefix:
+has same url path prefix. Application prefix always contains laading "/" slash.
+If supplied prefix does not contain leading slash, it get inserted.
+Prefix should consists of valud path segments. i.e for application with prefix `/app`
+any request with following paths `/app`, `/app/` or `/app/test` would match,
+but path `/application` would not match.
```rust,ignore
- let app = Application::default("/prefix")
- .resource("/index.html", |r| r.handler(Method::GET, index)
+# extern crate actix_web;
+# extern crate tokio_core;
+# use actix_web::*;
+# fn index(req: HttpRequest) -> &'static str {
+# "Hello world!"
+# }
+# fn main() {
+ let app = Application::new()
+ .prefix("/app")
+ .resource("/index.html", |r| r.method(Method::GET).f(index))
.finish()
+# }
```
-In this example application with `/prefix` prefix and `index.html` resource
-get created. This resource is available as on `/prefix/index.html` url.
+In this example application with `/app` prefix and `index.html` resource
+get created. This resource is available as on `/app/index.html` url.
+For more information check
+[*URL Matching*](./qs_5.html#using-a-application-prefix-to-compose-applications) section.
Multiple applications could be served with one server:
```rust
-extern crate actix_web;
-extern crate tokio_core;
-use std::net::SocketAddr;
+# extern crate actix_web;
+# extern crate tokio_core;
+# use tokio_core::net::TcpStream;
+# use std::net::SocketAddr;
use actix_web::*;
-use tokio_core::net::TcpStream;
fn main() {
- HttpServer::::new(vec![
- Application::default("/app1")
- .resource("/", |r| r.get(|r| httpcodes::HTTPOk))
- .finish(),
- Application::default("/app2")
- .resource("/", |r| r.get(|r| httpcodes::HTTPOk))
- .finish(),
- Application::default("/")
- .resource("/", |r| r.get(|r| httpcodes::HTTPOk))
- .finish(),
+ HttpServer::::new(|| vec![
+ Application::new()
+ .prefix("/app1")
+ .resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
+ Application::new()
+ .prefix("/app2")
+ .resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
+ Application::new()
+ .resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
]);
}
```
All `/app1` requests route to first application, `/app2` to second and then all other to third.
+Applications get matched based on registration order, if application with more general
+prefix is registered before less generic, that would effectively block less generic
+application to get matched. For example if *application* with prefix "/" get registered
+as first application, it would match all incoming requests.
+
+## State
+
+Application state is shared with all routes and resources within same application.
+State could be accessed with `HttpRequest::state()` method as a read-only item
+but interior mutability pattern with `RefCell` could be used to archive state mutability.
+State could be accessed with `HttpContext::state()` in case of http actor.
+State also available to route matching predicates and middlewares.
+
+Let's write simple application that uses shared state. We are going to store requests count
+in the state:
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+#
+use actix_web::*;
+use std::cell::Cell;
+
+// This struct represents state
+struct AppState {
+ counter: Cell,
+}
+
+fn index(req: HttpRequest) -> String {
+ let count = req.state().counter.get() + 1; // <- get count
+ req.state().counter.set(count); // <- store new count in state
+
+ format!("Request number: {}", count) // <- response with count
+}
+
+fn main() {
+ Application::with_state(AppState{counter: Cell::new(0)})
+ .resource("/", |r| r.method(Method::GET).f(index))
+ .finish();
+}
+```
+
+Note on application state, http server accepts application factory rather than application
+instance. Http server construct application instance for each thread, so application state
+must be constructed multiple times. If you want to share state between different thread
+shared object should be used, like `Arc`. Application state does not need to be `Send` and `Sync`
+but application factory must be `Send` + `Sync`.
diff --git a/guide/src/qs_3_5.md b/guide/src/qs_3_5.md
new file mode 100644
index 000000000..580f029d9
--- /dev/null
+++ b/guide/src/qs_3_5.md
@@ -0,0 +1,197 @@
+# Server
+
+[*HttpServer*](../actix_web/struct.HttpServer.html) type is responsible for
+serving http requests. *HttpServer* accept application factory as a parameter,
+Application factory must have `Send` + `Sync` bounderies. More about that in
+*multi-threading* section. To bind to specific socket address `bind()` must be used.
+This method could be called multiple times. To start http server one of the *start*
+methods could be used. `start()` method start simple server, `start_tls()` or `start_ssl()`
+starts ssl server. *HttpServer* is an actix actor, it has to be initialized
+within properly configured actix system:
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+use actix::*;
+use actix_web::*;
+
+fn main() {
+ let sys = actix::System::new("guide");
+
+ HttpServer::new(
+ || Application::new()
+ .resource("/", |r| r.h(httpcodes::HTTPOk)))
+ .bind("127.0.0.1:59080").unwrap()
+ .start();
+
+# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
+ let _ = sys.run();
+}
+```
+
+It is possible to start server in separate thread with *spawn()* method. In that
+case server spawns new thread and create new actix system in it. To stop
+this server send `StopServer` message.
+
+Http server is implemented as an actix actor. It is possible to communicate with server
+via messaging system. All start methods like `start()`, `start_ssl()`, etc returns
+address of the started http server. Actix http server accept several messages:
+
+* `PauseServer` - Pause accepting incoming connections
+* `ResumeServer` - Resume accepting incoming connections
+* `StopServer` - Stop incoming connection processing, stop all workers and exit
+
+```rust
+# extern crate futures;
+# extern crate actix;
+# extern crate actix_web;
+# use futures::Future;
+use actix_web::*;
+use std::thread;
+use std::sync::mpsc;
+
+fn main() {
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let sys = actix::System::new("http-server");
+ let addr = HttpServer::new(
+ || Application::new()
+ .resource("/", |r| r.h(httpcodes::HTTPOk)))
+ .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
+ .shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
+ .start();
+ let _ = tx.send(addr);
+ let _ = sys.run();
+ });
+
+ let addr = rx.recv().unwrap();
+ let _ = addr.call_fut(
+ dev::StopServer{graceful:true}).wait(); // <- Send `StopServer` message to server.
+}
+```
+
+## Multi-threading
+
+Http server automatically starts number of http workers, by default
+this number is equal to number of logical cpu in the system. This number
+could be overridden with `HttpServer::threads()` method.
+
+```rust
+# extern crate actix_web;
+# extern crate tokio_core;
+# use tokio_core::net::TcpStream;
+# use std::net::SocketAddr;
+use actix_web::*;
+
+fn main() {
+ HttpServer::::new(
+ || Application::new()
+ .resource("/", |r| r.h(httpcodes::HTTPOk)))
+ .threads(4); // <- Start 4 workers
+}
+```
+
+Server create separate application instance for each created worker. Application state
+is not shared between threads, to share state `Arc` could be used. Application state
+does not need to be `Send` and `Sync` but application factory must be `Send` + `Sync`.
+
+## SSL
+
+There are two `tls` and `alpn` features for ssl server. `tls` feature is for `native-tls`
+integration and `alpn` is for `openssl`.
+
+```toml
+[dependencies]
+actix-web = { git = "https://github.com/actix/actix-web", features=["alpn"] }
+```
+
+```rust,ignore
+use std::fs::File;
+use actix_web::*;
+
+fn main() {
+ let mut file = File::open("identity.pfx").unwrap();
+ let mut pkcs12 = vec![];
+ file.read_to_end(&mut pkcs12).unwrap();
+ let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
+
+ HttpServer::new(
+ || Application::new()
+ .resource("/index.html", |r| r.f(index)))
+ .bind("127.0.0.1:8080").unwrap()
+ .serve_ssl(pkcs12).unwrap();
+}
+```
+
+Note on *HTTP/2.0* protocol over tls without prior knowledge, it requires
+[tls alpn](https://tools.ietf.org/html/rfc7301). At the moment only
+`openssl` has `alpn ` support.
+
+Please check [example](https://github.com/actix/actix-web/tree/master/examples/tls)
+for full example.
+
+## Keep-Alive
+
+Actix can wait for requests on a keep-alive connection. *Keep alive*
+connection behavior is defined by server settings.
+
+ * `Some(75)` - enable 75 sec *keep alive* timer according request and response settings.
+ * `Some(0)` - disable *keep alive*.
+ * `None` - Use `SO_KEEPALIVE` socket option.
+
+```rust
+# extern crate actix_web;
+# extern crate tokio_core;
+# use tokio_core::net::TcpStream;
+# use std::net::SocketAddr;
+use actix_web::*;
+
+fn main() {
+ HttpServer::::new(||
+ Application::new()
+ .resource("/", |r| r.h(httpcodes::HTTPOk)))
+ .keep_alive(None); // <- Use `SO_KEEPALIVE` socket option.
+}
+```
+
+If first option is selected then *keep alive* state
+calculated based on response's *connection-type*. By default
+`HttpResponse::connection_type` is not defined in that case *keep alive*
+defined by request's http version. Keep alive is off for *HTTP/1.0*
+and is on for *HTTP/1.1* and "HTTP/2.0".
+
+*Connection type* could be change with `HttpResponseBuilder::connection_type()` method.
+
+```rust
+# extern crate actix_web;
+# use actix_web::httpcodes::*;
+use actix_web::*;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ HTTPOk.build()
+ .connection_type(headers::ConnectionType::Close) // <- Close connection
+ .force_close() // <- Alternative method
+ .finish().unwrap()
+}
+# fn main() {}
+```
+
+## Graceful shutdown
+
+Actix http server support graceful shutdown. After receiving a stop signal, workers
+have specific amount of time to finish serving requests. Workers still alive after the
+timeout are force dropped. By default shutdown timeout sets to 30 seconds.
+You can change this parameter with `HttpServer::shutdown_timeout()` method.
+
+You can send stop message to server with server address and specify if you what
+graceful shutdown or not. `start()` methods return address of the server.
+
+Http server handles several OS signals. *CTRL-C* is available on all OSs,
+other signals are available on unix systems.
+
+* *SIGINT* - Force shutdown workers
+* *SIGTERM* - Graceful shutdown workers
+* *SIGQUIT* - Force shutdown workers
+
+It is possible to disable signals handling with `HttpServer::disable_signals()` method.
diff --git a/guide/src/qs_4.md b/guide/src/qs_4.md
index 969d01b8f..42afb9219 100644
--- a/guide/src/qs_4.md
+++ b/guide/src/qs_4.md
@@ -1,21 +1,19 @@
# Handler
-A request handler can by any object that implements
-[`Handler` trait](../actix_web/struct.HttpResponse.html#implementations).
+A request handler can by any object that implements
+[*Handler trait*](../actix_web/dev/trait.Handler.html).
+Request handling happen in two stages. First handler object get called.
+Handle can return any object that implements
+[*Responder trait*](../actix_web/trait.Responder.html#foreign-impls).
+Then `respond_to()` get called on returned object. And finally
+result of the `respond_to()` call get converted to `Reply` object.
-By default actix provdes several `Handler` implementations:
-
-* Simple function that accepts `HttpRequest` and returns any object that
- can be converted to `HttpResponse`
-* Function that accepts `HttpRequest` and returns `Result>` object.
-* Function that accepts `HttpRequest` and return actor that has `HttpContext`as a context.
-
-Actix provides response conversion into `HttpResponse` for some standard types,
+By default actix provides `Responder` implementations for some standard types,
like `&'static str`, `String`, etc.
For complete list of implementations check
-[HttpResponse documentation](../actix_web/struct.HttpResponse.html#implementations).
+[*Responder documentation*](../actix_web/trait.Responder.html#foreign-impls).
-Examples:
+Examples of valid handlers:
```rust,ignore
fn index(req: HttpRequest) -> &'static str {
@@ -41,13 +39,95 @@ fn index(req: HttpRequest) -> Box> {
}
```
-## Custom conversion
+Some notes on shared application state and handler state. If you noticed
+*Handler* trait is generic over *S*, which defines application state type. So
+application state is accessible from handler with `HttpRequest::state()` method.
+But state is accessible as a read-only reference, if you need mutable access to state
+you have to implement it yourself. On other hand handler can mutable access it's own state
+as `handle` method takes mutable reference to *self*. Beware, actix creates multiple copies
+of application state and handlers, unique for each thread, so if you run your
+application in several threads actix will create same amount as number of threads
+of application state objects and handler objects.
+Here is example of handler that stores number of processed requests:
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+use actix_web::*;
+use actix_web::dev::Handler;
+
+struct MyHandler(usize);
+
+impl Handler for MyHandler {
+ type Result = HttpResponse;
+
+ /// Handle request
+ fn handle(&mut self, req: HttpRequest) -> Self::Result {
+ self.0 += 1;
+ httpcodes::HTTPOk.into()
+ }
+}
+# fn main() {}
+```
+
+This handler will work, but `self.0` value will be different depends on number of threads and
+number of requests processed per thread. Proper implementation would use `Arc` and `AtomicUsize`
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+use actix_web::*;
+use actix_web::dev::Handler;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct MyHandler(Arc);
+
+impl Handler for MyHandler {
+ type Result = HttpResponse;
+
+ /// Handle request
+ fn handle(&mut self, req: HttpRequest) -> Self::Result {
+ let num = self.0.load(Ordering::Relaxed) + 1;
+ self.0.store(num, Ordering::Relaxed);
+ httpcodes::HTTPOk.into()
+ }
+}
+
+fn main() {
+ let sys = actix::System::new("example");
+
+ let inc = Arc::new(AtomicUsize::new(0));
+
+ HttpServer::new(
+ move || {
+ let cloned = inc.clone();
+ Application::new()
+ .resource("/", move |r| r.h(MyHandler(cloned)))
+ })
+ .bind("127.0.0.1:8088").unwrap()
+ .start();
+
+ println!("Started http server: 127.0.0.1:8088");
+# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
+ let _ = sys.run();
+}
+```
+
+Be careful with synchronization primitives like *Mutex* or *RwLock*. Actix web framework
+handles request asynchronously, by blocking thread execution all concurrent
+request handling processes would block. If you need to share or update some state
+from multiple threads consider using [actix](https://actix.github.io/actix/actix/) actor system.
+
+## Response with custom type
+
+To return custom type directly from handler function, type needs to implement `Responder` trait.
Let's create response for custom type that serializes to `application/json` response:
```rust
-extern crate actix;
-extern crate actix_web;
+# extern crate actix;
+# extern crate actix_web;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
@@ -55,87 +135,101 @@ use actix_web::*;
#[derive(Serialize)]
struct MyObj {
- name: String,
+ name: &'static str,
}
-/// we have to convert Error into HttpResponse as well, but with
-/// specialization this could be handled genericly.
-impl Into for MyObj {
- fn into(self) -> HttpResponse {
- let body = match serde_json::to_string(&self) {
- Err(err) => return Error::from(err).into(),
- Ok(body) => body,
- };
+/// Responder
+impl Responder for MyObj {
+ type Item = HttpResponse;
+ type Error = Error;
+
+ fn respond_to(self, req: HttpRequest) -> Result {
+ let body = serde_json::to_string(&self)?;
// Create response and set content type
- HttpResponse::Ok()
+ Ok(HttpResponse::Ok()
.content_type("application/json")
- .body(body).unwrap()
+ .body(body)?)
}
}
+/// Because `MyObj` implements `Responder`, it is possible to return it directly
+fn index(req: HttpRequest) -> MyObj {
+ MyObj{name: "user"}
+}
+
fn main() {
let sys = actix::System::new("example");
HttpServer::new(
- Application::default("/")
- .resource("/", |r| r.handler(
- Method::GET, |req| {MyObj{name: "user".to_owned()}})))
- .serve::<_, ()>("127.0.0.1:8088").unwrap();
+ || Application::new()
+ .resource("/", |r| r.method(Method::GET).f(index)))
+ .bind("127.0.0.1:8088").unwrap()
+ .start();
println!("Started http server: 127.0.0.1:8088");
- actix::Arbiter::system().send(actix::msgs::SystemExit(0)); // <- remove this line, this code stops system during testing
-
+# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
let _ = sys.run();
}
```
-If `specialization` is enabled, conversion could be simplier:
-
-```rust,ignore
-impl Into> for MyObj {
- fn into(self) -> Result {
- let body = serde_json::to_string(&self)?;
-
- Ok(HttpResponse::Ok()
- .content_type("application/json")
- .body(body)?)
- }
-}
-```
-
## Async handlers
There are two different types of async handlers.
-Response object could be generated asynchronously. In this case handle must
-return `Future` object that resolves to `HttpResponse`, i.e:
+Response object could be generated asynchronously or more precisely, any type
+that implements [*Responder*](../actix_web/trait.Responder.html) trait. In this case handle must
+return `Future` object that resolves to *Responder* type, i.e:
-```rust,ignore
-fn index(req: HttpRequest) -> Box> {
- ...
+```rust
+# extern crate actix_web;
+# extern crate futures;
+# extern crate bytes;
+# use actix_web::*;
+# use bytes::Bytes;
+# use futures::stream::once;
+# use futures::future::{FutureResult, result};
+fn index(req: HttpRequest) -> FutureResult {
+
+ result(HttpResponse::Ok()
+ .content_type("text/html")
+ .body(format!("Hello!"))
+ .map_err(|e| e.into()))
+}
+
+fn index2(req: HttpRequest) -> FutureResult<&'static str, Error> {
+ result(Ok("Welcome!"))
+}
+
+fn main() {
+ Application::new()
+ .resource("/async", |r| r.route().a(index))
+ .resource("/", |r| r.route().a(index2))
+ .finish();
}
```
-This handler can be registered with `ApplicationBuilder::async()` and
-`Resource::async()` methods.
-
Or response body can be generated asynchronously. In this case body
must implement stream trait `Stream- `, i.e:
-
-```rust,ignore
+```rust
+# extern crate actix_web;
+# extern crate futures;
+# extern crate bytes;
+# use actix_web::*;
+# use bytes::Bytes;
+# use futures::stream::once;
fn index(req: HttpRequest) -> HttpResponse {
- let body: Box> = Box::new(SomeStream::new());
+ let body = once(Ok(Bytes::from_static(b"test")));
- HttpResponse::Ok().
+ HttpResponse::Ok()
.content_type("application/json")
- .body(Body::Streaming(body)).unwrap()
+ .body(Body::Streaming(Box::new(body))).unwrap()
}
fn main() {
- Application::default("/")
- .async("/async", index)
+ Application::new()
+ .resource("/async", |r| r.f(index))
.finish();
}
```
diff --git a/guide/src/qs_4_5.md b/guide/src/qs_4_5.md
new file mode 100644
index 000000000..ef3a982ae
--- /dev/null
+++ b/guide/src/qs_4_5.md
@@ -0,0 +1,136 @@
+# Errors
+
+Actix uses [`Error` type](../actix_web/error/struct.Error.html)
+and [`ResponseError` trait](../actix_web/error/trait.ResponseError.html)
+for handling handler's errors.
+Any error that implements `ResponseError` trait can be returned as error value.
+*Handler* can return *Result* object, actix by default provides
+`Responder` implemenation for compatible result object. Here is implementation
+definition:
+
+```rust,ignore
+impl> Responder for Result
+```
+
+And any error that implements `ResponseError` can be converted into `Error` object.
+For example if *handler* function returns `io::Error`, it would be converted
+into `HTTPInternalServerError` response. Implementation for `io::Error` is provided
+by default.
+
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+use std::io;
+
+fn index(req: HttpRequest) -> io::Result {
+ Ok(fs::NamedFile::open("static/index.html")?)
+}
+#
+# fn main() {
+# Application::new()
+# .resource(r"/a/index.html", |r| r.f(index))
+# .finish();
+# }
+```
+
+## Custom error response
+
+To add support for custom errors, all we need to do is just implement `ResponseError` trait
+for custom error. `ResponseError` trait has default implementation
+for `error_response()` method, it generates *500* response.
+
+```rust
+# extern crate actix_web;
+#[macro_use] extern crate failure;
+use actix_web::*;
+
+#[derive(Fail, Debug)]
+#[fail(display="my error")]
+struct MyError {
+ name: &'static str
+}
+
+/// Use default implementation for `error_response()` method
+impl error::ResponseError for MyError {}
+
+fn index(req: HttpRequest) -> Result<&'static str, MyError> {
+ Err(MyError{name: "test"})
+}
+#
+# fn main() {
+# Application::new()
+# .resource(r"/a/index.html", |r| r.f(index))
+# .finish();
+# }
+```
+
+In this example *index* handler will always return *500* response. But it is easy
+to return different responses for different type of errors.
+
+```rust
+# extern crate actix_web;
+#[macro_use] extern crate failure;
+use actix_web::*;
+
+#[derive(Fail, Debug)]
+enum MyError {
+ #[fail(display="internal error")]
+ InternalError,
+ #[fail(display="bad request")]
+ BadClientData,
+ #[fail(display="timeout")]
+ Timeout,
+}
+
+impl error::ResponseError for MyError {
+ fn error_response(&self) -> HttpResponse {
+ match *self {
+ MyError::InternalError => HttpResponse::new(
+ StatusCode::INTERNAL_SERVER_ERROR, Body::Empty),
+ MyError::BadClientData => HttpResponse::new(
+ StatusCode::BAD_REQUEST, Body::Empty),
+ MyError::Timeout => HttpResponse::new(
+ StatusCode::GATEWAY_TIMEOUT, Body::Empty),
+ }
+ }
+}
+
+fn index(req: HttpRequest) -> Result<&'static str, MyError> {
+ Err(MyError::BadClientData)
+}
+#
+# fn main() {
+# Application::new()
+# .resource(r"/a/index.html", |r| r.f(index))
+# .finish();
+# }
+```
+
+## Error helpers
+
+Actix provides set of error helper types. It is possible to use them to generate
+specific error response. We can use helper types for first example with custom error.
+
+```rust
+# extern crate actix_web;
+#[macro_use] extern crate failure;
+use actix_web::*;
+
+#[derive(Debug)]
+struct MyError {
+ name: &'static str
+}
+
+fn index(req: HttpRequest) -> Result<&'static str> {
+ let result: Result<&'static str, MyError> = Err(MyError{name: "test"});
+
+ Ok(result.map_err(error::ErrorBadRequest)?)
+}
+# fn main() {
+# Application::new()
+# .resource(r"/a/index.html", |r| r.f(index))
+# .finish();
+# }
+```
+
+In this example *BAD REQUEST* response get generated for `MyError` error.
diff --git a/guide/src/qs_5.md b/guide/src/qs_5.md
index 157b55c57..1aa7edeb0 100644
--- a/guide/src/qs_5.md
+++ b/guide/src/qs_5.md
@@ -1,107 +1,578 @@
-# Resources and Routes
+# URL Dispatch
-All resources and routes register for specific application.
-Application routes incoming requests based on route criteria which is defined during
-resource registration or path prefix for simple handlers.
-Internally *router* is a list of *resources*. Resource is an entry in *route table*
-which corresponds to requested URL.
+URL dispatch provides a simple way to map URLs to `Handler` code using a simple pattern matching
+language. *Regex* crate and it's
+[*RegexSet*](https://doc.rust-lang.org/regex/regex/struct.RegexSet.html) is beeing used for
+pattern matching. If one of the patterns matches the path information associated with a request,
+a particular handler object is invoked. A handler is a specific object that implements
+`Handler` trait, defined in your application, that receives the request and returns
+a response object. More informatin is available in [handler section](../qs_4.html).
-Prefix handler:
+## Resource configuration
-```rust,ignore
-fn index(req: Httprequest) -> HttpResponse {
- ...
-}
+Resource configuraiton is the act of adding a new resource to an application.
+A resource has a name, which acts as an identifier to be used for URL generation.
+The name also allows developers to add routes to existing resources.
+A resource also has a pattern, meant to match against the *PATH* portion of a *URL*,
+it does not match against *QUERY* portion (the portion following the scheme and
+port, e.g., */foo/bar* in the *URL* *http://localhost:8080/foo/bar?q=value*).
+The [Application::resource](../actix_web/struct.Application.html#method.resource) methods
+add a single resource to application routing table. This method accepts *path pattern*
+and resource configuration funnction.
+
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+# use actix_web::httpcodes::*;
+#
+# fn index(req: HttpRequest) -> HttpResponse {
+# unimplemented!()
+# }
+#
fn main() {
- Application::default("/")
- .handler("/prefix", |req| index)
+ Application::new()
+ .resource("/prefix", |r| r.f(index))
+ .resource("/user/{name}",
+ |r| r.method(Method::GET).f(|req| HTTPOk))
.finish();
}
```
-In this example `index` get called for any url which starts with `/prefix`.
-
-Application prefix combines with handler prefix i.e
+*Configuraiton function* has following type:
```rust,ignore
+ FnOnce(&mut Resource<_>) -> ()
+```
+
+*Configration function* can set name and register specific routes.
+If resource does not contain any route or does not have any matching routes it
+returns *NOT FOUND* http resources.
+
+## Configuring a Route
+
+Resource contains set of routes. Each route in turn has set of predicates and handler.
+New route could be crearted with `Resource::route()` method which returns reference
+to new *Route* instance. By default *route* does not contain any predicates, so matches
+all requests and default handler is `HTTPNotFound`.
+
+Application routes incoming requests based on route criteria which is defined during
+resource registration and route registration. Resource matches all routes it contains in
+the order that the routes were registered via `Resource::route()`. *Route* can contain
+any number of *predicates* but only one handler.
+
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+# use actix_web::httpcodes::*;
+
fn main() {
- Application::default("/app")
- .handler("/prefix", |req| index)
+ Application::new()
+ .resource("/path", |resource|
+ resource.route()
+ .p(pred::Get())
+ .p(pred::Header("content-type", "text/plain"))
+ .f(|req| HTTPOk)
+ )
.finish();
}
```
-In this example `index` get called for any url which starts with`/app/prefix`.
+In this example `index` get called for *GET* request,
+if request contains `Content-Type` header and value of this header is *text/plain*
+and path equals to `/test`. Resource calls handle of the first matches route.
+If resource can not match any route "NOT FOUND" response get returned.
-Resource contains set of route for same endpoint. Route corresponds to handling
-*HTTP method* by calling *web handler*. Resource select route based on *http method*,
-if no route could be matched default response `HTTPMethodNotAllowed` get resturned.
+[*Resource::route()*](../actix_web/struct.Resource.html#method.route) method returns
+[*Route*](../actix_web/struct.Route.html) object. Route can be configured with
+builder-like pattern. Following configuration methods are available:
+
+* [*Route::p()*](../actix_web/struct.Route.html#method.p) method registers new predicate,
+ any number of predicates could be registered for each route.
+
+* [*Route::f()*](../actix_web/struct.Route.html#method.f) method registers handler function
+ for this route. Only one handler could be registered. Usually handler registeration
+ is the last config operation. Handler fanction could be function or closure and has type
+ `Fn(HttpRequest
) -> R + 'static`
+
+* [*Route::h()*](../actix_web/struct.Route.html#method.h) method registers handler object
+ that implements `Handler` trait. This is similar to `f()` method, only one handler could
+ be registered. Handler registeration is the last config operation.
+
+* [*Route::a()*](../actix_web/struct.Route.html#method.a) method registers asynchandler
+ function for this route. Only one handler could be registered. Handler registeration
+ is the last config operation. Handler fanction could be function or closure and has type
+ `Fn(HttpRequest) -> Future- + 'static`
+
+## Route matching
+
+The main purpose of route configuration is to match (or not match) the request's `path`
+against a URL path pattern. `path` represents the path portion of the URL that was requested.
+
+The way that *actix* does this is very simple. When a request enters the system,
+for each resource configuration registration present in the system, actix checks
+the request's path against the pattern declared. *Regex* crate and it's
+[*RegexSet*](https://doc.rust-lang.org/regex/regex/struct.RegexSet.html) is beeing used for
+pattern matching. If resource could not be found, *default resource* get used as matched
+resource.
+
+When a route configuration is declared, it may contain route predicate arguments. All route
+predicates associated with a route declaration must be `true` for the route configuration to
+be used for a given request during a check. If any predicate in the set of route predicate
+arguments provided to a route configuration returns `false` during a check, that route is
+skipped and route matching continues through the ordered set of routes.
+
+If any route matches, the route matching process stops and the handler associated with
+route get invoked.
+
+If no route matches after all route patterns are exhausted, *NOT FOUND* response get returned.
+
+## Resource pattern syntax
+
+The syntax of the pattern matching language used by the actix in the pattern
+argument is straightforward.
+
+The pattern used in route configuration may start with a slash character. If the pattern
+does not start with a slash character, an implicit slash will be prepended
+to it at matching time. For example, the following patterns are equivalent:
+
+```
+{foo}/bar/baz
+```
+
+and:
+
+```
+/{foo}/bar/baz
+```
+
+A *variable part* (replacement marker) is specified in the form *{identifier}*,
+where this means "accept any characters up to the next slash character and use this
+as the name in the `HttpRequest.match_info()` object".
+
+A replacement marker in a pattern matches the regular expression `[^{}/]+`.
+
+A match_info is the `Params` object representing the dynamic parts extracted from a
+*URL* based on the routing pattern. It is available as *request.match_info*. For example, the
+following pattern defines one literal segment (foo) and two replacement markers (baz, and bar):
+
+```
+foo/{baz}/{bar}
+```
+
+The above pattern will match these URLs, generating the following match information:
+
+```
+foo/1/2 -> Params {'baz':'1', 'bar':'2'}
+foo/abc/def -> Params {'baz':'abc', 'bar':'def'}
+```
+
+It will not match the following patterns however:
+
+```
+foo/1/2/ -> No match (trailing slash)
+bar/abc/def -> First segment literal mismatch
+```
+
+The match for a segment replacement marker in a segment will be done only up to
+the first non-alphanumeric character in the segment in the pattern. So, for instance,
+if this route pattern was used:
+
+```
+foo/{name}.html
+```
+
+The literal path */foo/biz.html* will match the above route pattern, and the match result
+will be `Params{'name': 'biz'}`. However, the literal path */foo/biz* will not match,
+because it does not contain a literal *.html* at the end of the segment represented
+by *{name}.html* (it only contains biz, not biz.html).
+
+To capture both segments, two replacement markers can be used:
+
+```
+foo/{name}.{ext}
+```
+
+The literal path */foo/biz.html* will match the above route pattern, and the match
+result will be *Params{'name': 'biz', 'ext': 'html'}*. This occurs because there is a
+literal part of *.* (period) between the two replacement markers *{name}* and *{ext}*.
+
+Replacement markers can optionally specify a regular expression which will be used to decide
+whether a path segment should match the marker. To specify that a replacement marker should
+match only a specific set of characters as defined by a regular expression, you must use a
+slightly extended form of replacement marker syntax. Within braces, the replacement marker
+name must be followed by a colon, then directly thereafter, the regular expression. The default
+regular expression associated with a replacement marker *[^/]+* matches one or more characters
+which are not a slash. For example, under the hood, the replacement marker *{foo}* can more
+verbosely be spelled as *{foo:[^/]+}*. You can change this to be an arbitrary regular expression
+to match an arbitrary sequence of characters, such as *{foo:\d+}* to match only digits.
+
+Segments must contain at least one character in order to match a segment replacement marker.
+For example, for the URL */abc/*:
+
+* */abc/{foo}* will not match.
+* */{foo}/* will match.
+
+Note that path will be URL-unquoted and decoded into valid unicode string before
+matching pattern and values representing matched path segments will be URL-unquoted too.
+So for instance, the following pattern:
+
+```
+foo/{bar}
+```
+
+When matching the following URL:
+
+```
+http://example.com/foo/La%20Pe%C3%B1a
+```
+
+The matchdict will look like so (the value is URL-decoded):
+
+```
+Params{'bar': 'La Pe\xf1a'}
+```
+
+Literal strings in the path segment should represent the decoded value of the
+path provided to actix. You don't want to use a URL-encoded value in the pattern.
+For example, rather than this:
+
+```
+/Foo%20Bar/{baz}
+```
+
+You'll want to use something like this:
+
+```
+/Foo Bar/{baz}
+```
+
+It is possible to get "tail match". For this purpose custom regex has to be used.
+
+```
+foo/{bar}/{tail:.*}
+```
+
+The above pattern will match these URLs, generating the following match information:
+
+```
+foo/1/2/ -> Params{'bar':'1', 'tail': '2/'}
+foo/abc/def/a/b/c -> Params{'bar':u'abc', 'tail': 'def/a/b/c'}
+```
+
+## Match information
+
+All values representing matched path segments are available in
+[`HttpRequest::match_info`](../actix_web/struct.HttpRequest.html#method.match_info).
+Specific value can be received with
+[`Params::get()`](../actix_web/dev/struct.Params.html#method.get) method.
+
+Any matched parameter can be deserialized into specific type if this type
+implements `FromParam` trait. For example most of standard integer types
+implements `FromParam` trait. i.e.:
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+
+fn index(req: HttpRequest) -> Result {
+ let v1: u8 = req.match_info().query("v1")?;
+ let v2: u8 = req.match_info().query("v2")?;
+ Ok(format!("Values {} {}", v1, v2))
+}
-```rust,ignore
fn main() {
- Application::default("/")
- .resource("/prefix", |r| {
- r.get(HTTPOk)
- r.post(HTTPForbidden)
+ Application::new()
+ .resource(r"/a/{v1}/{v2}/", |r| r.f(index))
+ .finish();
+}
+```
+
+For this example for path '/a/1/2/', values v1 and v2 will resolve to "1" and "2".
+
+It is possible to create a `PathBuf` from a tail path parameter. The returned `PathBuf` is
+percent-decoded. If a segment is equal to "..", the previous segment (if
+any) is skipped.
+
+For security purposes, if a segment meets any of the following conditions,
+an `Err` is returned indicating the condition met:
+
+ * Decoded segment starts with any of: `.` (except `..`), `*`
+ * Decoded segment ends with any of: `:`, `>`, `<`
+ * Decoded segment contains any of: `/`
+ * On Windows, decoded segment contains any of: '\'
+ * Percent-encoding results in invalid UTF8.
+
+As a result of these conditions, a `PathBuf` parsed from request path parameter is
+safe to interpolate within, or use as a suffix of, a path without additional checks.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+use std::path::PathBuf;
+
+fn index(req: HttpRequest) -> Result {
+ let path: PathBuf = req.match_info().query("tail")?;
+ Ok(format!("Path {:?}", path))
+}
+
+fn main() {
+ Application::new()
+ .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
+ .finish();
+}
+```
+
+List of `FromParam` implementation could be found in
+[api docs](../actix_web/dev/trait.FromParam.html#foreign-impls)
+
+## Generating resource URLs
+
+Use the [HttpRequest.url_for()](../actix_web/struct.HttpRequest.html#method.url_for)
+method to generate URLs based on resource patterns. For example, if you've configured a
+resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this.
+
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+# use actix_web::httpcodes::*;
+#
+fn index(req: HttpRequest) -> HttpResponse {
+ let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
+ HTTPOk.into()
+}
+
+fn main() {
+ let app = Application::new()
+ .resource("/test/{a}/{b}/{c}", |r| {
+ r.name("foo"); // <- set resource name, then it could be used in `url_for`
+ r.method(Method::GET).f(|_| httpcodes::HTTPOk);
})
.finish();
}
```
-[`ApplicationBuilder::resource()` method](../actix_web/dev/struct.ApplicationBuilder.html#method.resource)
-accepts configuration function, resource could be configured at once.
-Check [`Resource`](../actix-web/target/doc/actix_web/struct.Resource.html) documentation
-for more information.
+This would return something like the string *http://example.com/test/1/2/3* (at least if
+the current protocol and hostname implied http://example.com).
+`url_for()` method return [*Url object*](https://docs.rs/url/1.6.0/url/struct.Url.html) so you
+can modify this url (add query parameters, anchor, etc).
+`url_for()` could be called only for *named* resources otherwise error get returned.
-## Variable resources
-
-Resource may have *variable path*also. For instance, a resource with the
-path '/a/{name}/c' would match all incoming requests with paths such
-as '/a/b/c', '/a/1/c', and '/a/etc/c'.
-
-A *variable part*is specified in the form {identifier}, where the identifier can be
-used later in a request handler to access the matched value for that part. This is
-done by looking up the identifier in the `HttpRequest.match_info` object:
+## External resources
+Resources that are valid URLs, could be registered as external resources. They are useful
+for URL generation purposes only and are never considered for matching at request time.
```rust
-extern crate actix;
+# extern crate actix_web;
use actix_web::*;
-fn index(req: Httprequest) -> String {
- format!("Hello, {}", req.match_info.get('name').unwrap())
+fn index(mut req: HttpRequest) -> Result {
+ let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
+ assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
+ Ok(httpcodes::HTTPOk.into())
}
fn main() {
- Application::default("/")
- .resource("/{name}", |r| r.get(index))
+ let app = Application::new()
+ .resource("/index.html", |r| r.f(index))
+ .external_resource("youtube", "https://youtube.com/watch/{video_id}")
.finish();
}
```
-By default, each part matches the regular expression `[^{}/]+`.
+## Path normalization and redirecting to slash-appended routes
-You can also specify a custom regex in the form `{identifier:regex}`:
+By normalizing it means:
+
+ - Add a trailing slash to the path.
+ - Double slashes are replaced by one.
+
+The handler returns as soon as it finds a path that resolves
+correctly. The order if all enable is 1) merge, 3) both merge and append
+and 3) append. If the path resolves with
+at least one of those conditions, it will redirect to the new path.
+
+If *append* is *true* append slash when needed. If a resource is
+defined with trailing slash and the request comes without it, it will
+append it automatically.
+
+If *merge* is *true*, merge multiple consecutive slashes in the path into one.
+
+This handler designed to be use as a handler for application's *default resource*.
+
+```rust
+# extern crate actix_web;
+# #[macro_use] extern crate serde_derive;
+# use actix_web::*;
+#
+# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
+# httpcodes::HTTPOk
+# }
+fn main() {
+ let app = Application::new()
+ .resource("/resource/", |r| r.f(index))
+ .default_resource(|r| r.h(NormalizePath::default()))
+ .finish();
+}
+```
+
+In this example `/resource`, `//resource///` will be redirected to `/resource/` url.
+
+In this example path normalization handler get registered for all method,
+but you should not rely on this mechanism to redirect *POST* requests. The redirect of the
+slash-appending *Not Found* will turn a *POST* request into a GET, losing any
+*POST* data in the original request.
+
+It is possible to register path normalization only for *GET* requests only
+
+```rust
+# extern crate actix_web;
+# #[macro_use] extern crate serde_derive;
+# use actix_web::*;
+#
+# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
+# httpcodes::HTTPOk
+# }
+fn main() {
+ let app = Application::new()
+ .resource("/resource/", |r| r.f(index))
+ .default_resource(|r| r.method(Method::GET).h(NormalizePath::default()))
+ .finish();
+}
+```
+
+## Using a Application Prefix to Compose Applications
+
+The `Application::prefix()`" method allows to set specific application prefix.
+This prefix represents a resource prefix that will be prepended to all resource patterns added
+by the resource configuration. This can be used to help mount a set of routes at a different
+location than the included callable's author intended while still maintaining the same
+resource names.
+
+For example:
+
+```rust
+# extern crate actix_web;
+# use actix_web::*;
+#
+fn show_users(req: HttpRequest) -> HttpResponse {
+ unimplemented!()
+}
+
+fn main() {
+ Application::new()
+ .prefix("/users")
+ .resource("/show", |r| r.f(show_users))
+ .finish();
+}
+```
+
+In the above example, the *show_users* route will have an effective route pattern of
+*/users/show* instead of */show* because the application's prefix argument will be prepended
+to the pattern. The route will then only match if the URL path is */users/show*,
+and when the `HttpRequest.url_for()` function is called with the route name show_users,
+it will generate a URL with that same path.
+
+## Custom route predicates
+
+You can think of predicate as simple function that accept *request* object reference
+and returns *true* or *false*. Formally predicate is any object that implements
+[`Predicate`](../actix_web/pred/trait.Predicate.html) trait. Actix provides
+several predicates, you can check [functions section](../actix_web/pred/index.html#functions)
+of api docs.
+
+Here is simple predicates that check that request contains specific *header*:
+
+```rust
+# extern crate actix_web;
+# extern crate http;
+# use actix_web::*;
+# use actix_web::httpcodes::*;
+use http::header::CONTENT_TYPE;
+use actix_web::pred::Predicate;
+
+struct ContentTypeHeader;
+
+impl Predicate
for ContentTypeHeader {
+
+ fn check(&self, req: &mut HttpRequest) -> bool {
+ req.headers().contains_key(CONTENT_TYPE)
+ }
+}
+
+fn main() {
+ Application::new()
+ .resource("/index.html", |r|
+ r.route()
+ .p(ContentTypeHeader)
+ .h(HTTPOk));
+}
+```
+
+In this example *index* handler will be called only if request contains *CONTENT-TYPE* header.
+
+Predicates can have access to application's state via `HttpRequest::state()` method.
+Also predicates can store extra information in
+[requests`s extensions](../actix_web/struct.HttpRequest.html#method.extensions).
+
+### Modifing predicate values
+
+You can invert the meaning of any predicate value by wrapping it in a `Not` predicate.
+For example if you want to return "METHOD NOT ALLOWED" response for all methods
+except "GET":
+
+```rust
+# extern crate actix_web;
+# extern crate http;
+# use actix_web::*;
+# use actix_web::httpcodes::*;
+use actix_web::pred;
+
+fn main() {
+ Application::new()
+ .resource("/index.html", |r|
+ r.route()
+ .p(pred::Not(pred::Get()))
+ .f(|req| HTTPMethodNotAllowed))
+ .finish();
+}
+```
+
+`Any` predicate accept list of predicates and matches if any of the supplied
+predicates match. i.e:
```rust,ignore
-fn main() {
- Application::default("/")
- .resource(r"{name:\d+}", |r| r.get(index))
- .finish();
-}
+ pred::Any(pred::Get()).or(pred::Post())
```
-To match path tail, `{tail:*}` pattern could be used. Tail pattern has to be last
-segment in path otherwise it panics.
+`All` predicate accept list of predicates and matches if all of the supplied
+predicates match. i.e:
```rust,ignore
-fn main() {
- Application::default("/")
- .resource(r"/test/{tail:*}", |r| r.get(index))
- .finish();
-}
+ pred::All(pred::Get()).and(pred::Header("content-type", "plain/text"))
```
-Above example would match all incoming requests with path such as
-'/test/b/c', '/test/index.html', and '/test/etc/test'.
+## Changing the default Not Found response
+
+If path pattern can not be found in routing table or resource can not find matching
+route, default resource is used. Default response is *NOT FOUND* response.
+It is possible to override *NOT FOUND* response with `Application::default_resource()` method.
+This method accepts *configuration function* same as normal resource configuration
+with `Application::resource()` method.
+
+```rust
+# extern crate actix_web;
+# extern crate http;
+use actix_web::*;
+use actix_web::httpcodes::*;
+
+fn main() {
+ Application::new()
+ .default_resource(|r| {
+ r.method(Method::GET).f(|req| HTTPNotFound);
+ r.route().p(pred::Not(pred::Get())).f(|req| HTTPMethodNotAllowed);
+ })
+# .finish();
+}
+```
diff --git a/guide/src/qs_6.md b/guide/src/qs_6.md
deleted file mode 100644
index 8060e455a..000000000
--- a/guide/src/qs_6.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Application state
-
-Application state is shared with all routes within same application.
-State could be accessed with `HttpRequest::state()` method. It is read-only
-but interior mutability pattern with `RefCell` could be used to archive state mutability.
-State could be accessed with `HttpRequest::state()` method or
-`HttpContext::state()` in case of http actor.
-
-Let's write simple application that uses shared state. We are going to store requests count
-in the state:
-
-```rust
-extern crate actix;
-extern crate actix_web;
-
-use std::cell::Cell;
-use actix_web::*;
-
-// This struct represents state
-struct AppState {
- counter: Cell,
-}
-
-fn index(req: HttpRequest) -> String {
- let count = req.state().counter.get() + 1; // <- get count
- req.state().counter.set(count); // <- store new count in state
-
- format!("Request number: {}", count) // <- response with count
-}
-
-fn main() {
- Application::build("/", AppState{counter: Cell::new(0)})
- .resource("/", |r| r.handler(Method::GET, index))
- .finish();
-}
-```
diff --git a/guide/src/qs_7.md b/guide/src/qs_7.md
index 0d92e9fdd..7cce5932b 100644
--- a/guide/src/qs_7.md
+++ b/guide/src/qs_7.md
@@ -1 +1,297 @@
-# Request
+# Request & Response
+
+## Response
+
+Builder-like patter is used to construct an instance of `HttpResponse`.
+`HttpResponse` provides several method that returns `HttpResponseBuilder` instance,
+which is implements various convinience methods that helps build response.
+Check [documentation](../actix_web/dev/struct.HttpResponseBuilder.html)
+for type description. Methods `.body`, `.finish`, `.json` finalizes response creation and
+returns constructed *HttpResponse* instance. if this methods get called for the same
+builder instance multiple times, builder will panic.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+use actix_web::headers::ContentEncoding;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok()
+ .content_encoding(ContentEncoding::Br)
+ .content_type("plain/text")
+ .header("X-Hdr", "sample")
+ .body("data").unwrap()
+}
+# fn main() {}
+```
+
+## Content encoding
+
+Actix automatically *compress*/*decompress* payload. Following codecs are supported:
+
+ * Brotli
+ * Gzip
+ * Deflate
+ * Identity
+
+ If request headers contains `Content-Encoding` header, request payload get decompressed
+ according to header value. Multiple codecs are not supported, i.e: `Content-Encoding: br, gzip`.
+
+Response payload get compressed based on *content_encoding* parameter.
+By default `ContentEncoding::Auto` is used. If `ContentEncoding::Auto` is selected
+then compression depends on request's `Accept-Encoding` header.
+`ContentEncoding::Identity` could be used to disable compression.
+If other content encoding is selected the compression is enforced for this codec. For example,
+to enable `brotli` response's body compression use `ContentEncoding::Br`:
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+use actix_web::headers::ContentEncoding;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok()
+ .content_encoding(ContentEncoding::Br)
+ .body("data").unwrap()
+}
+# fn main() {}
+```
+
+
+## JSON Request
+
+There are two options of json body deserialization.
+
+First option is to use *HttpResponse::json()* method. This method returns
+[*JsonBody*](../actix_web/dev/struct.JsonBody.html) object which resolves into
+deserialized value.
+
+```rust
+# extern crate actix;
+# extern crate actix_web;
+# extern crate futures;
+# extern crate serde_json;
+# #[macro_use] extern crate serde_derive;
+# use actix_web::*;
+# use futures::Future;
+#[derive(Debug, Serialize, Deserialize)]
+struct MyObj {
+ name: String,
+ number: i32,
+}
+
+fn index(mut req: HttpRequest) -> Box> {
+ req.json().from_err()
+ .and_then(|val: MyObj| {
+ println!("model: {:?}", val);
+ Ok(httpcodes::HTTPOk.build().json(val)?) // <- send response
+ })
+ .responder()
+}
+# fn main() {}
+```
+
+Or you can manually load payload into memory and ther deserialize it.
+Here is simple example. We will deserialize *MyObj* struct. We need to load request
+body first and then deserialize json into object.
+
+```rust
+# extern crate actix_web;
+# extern crate futures;
+# use actix_web::*;
+# #[macro_use] extern crate serde_derive;
+extern crate serde_json;
+use futures::{Future, Stream};
+
+#[derive(Serialize, Deserialize)]
+struct MyObj {name: String, number: i32}
+
+fn index(mut req: HttpRequest) -> Box> {
+ // `concat2` will asynchronously read each chunk of the request body and
+ // return a single, concatenated, chunk
+ req.payload_mut().readany().concat2()
+ // `Future::from_err` acts like `?` in that it coerces the error type from
+ // the future into the final error type
+ .from_err()
+ // `Future::and_then` can be used to merge an asynchronous workflow with a
+ // synchronous workflow
+ .and_then(|body| { // <- body is loaded, now we can deserialize json
+ let obj = serde_json::from_slice::(&body)?;
+ Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
+ })
+ .responder()
+}
+# fn main() {}
+```
+
+Complete example for both options is available in
+[examples directory](https://github.com/actix/actix-web/tree/master/examples/json/).
+
+
+## JSON Response
+
+The `Json` type allows you to respond with well-formed JSON data: simply return a value of
+type Json where T is the type of a structure to serialize into *JSON*. The
+type `T` must implement the `Serialize` trait from *serde*.
+
+```rust
+# extern crate actix_web;
+#[macro_use] extern crate serde_derive;
+use actix_web::*;
+
+#[derive(Serialize)]
+struct MyObj {
+ name: String,
+}
+
+fn index(req: HttpRequest) -> Result> {
+ Ok(Json(MyObj{name: req.match_info().query("name")?}))
+}
+
+fn main() {
+ Application::new()
+ .resource(r"/a/{name}", |r| r.method(Method::GET).f(index))
+ .finish();
+}
+```
+
+## Chunked transfer encoding
+
+Actix automatically decode *chunked* encoding. `HttpRequest::payload()` already contains
+decoded bytes stream. If request payload compressed with one of supported
+compression codecs (br, gzip, deflate) bytes stream get decompressed.
+
+Chunked encoding on response could be enabled with `HttpResponseBuilder::chunked()` method.
+But this takes effect only for `Body::Streaming(BodyStream)` or `Body::StreamingContext` bodies.
+Also if response payload compression is enabled and streaming body is used, chunked encoding
+get enabled automatically.
+
+Enabling chunked encoding for *HTTP/2.0* responses is forbidden.
+
+```rust
+# extern crate actix_web;
+use actix_web::*;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok()
+ .chunked()
+ .body(Body::Streaming(payload::Payload::empty().stream())).unwrap()
+}
+# fn main() {}
+```
+
+## Multipart body
+
+Actix provides multipart stream support.
+[*Multipart*](../actix_web/multipart/struct.Multipart.html) is implemented as
+a stream of multipart items, each item could be
+[*Field*](../actix_web/multipart/struct.Field.html) or nested *Multipart* stream.
+`HttpResponse::multipart()` method returns *Multipart* stream for current request.
+
+In simple form multipart stream handling could be implemented similar to this example
+
+```rust,ignore
+# extern crate actix_web;
+use actix_web::*;
+
+fn index(req: HttpRequest) -> Box> {
+ req.multipart() // <- get multipart stream for current request
+ .and_then(|item| { // <- iterate over multipart items
+ match item {
+ // Handle multipart Field
+ multipart::MultipartItem::Field(field) => {
+ println!("==== FIELD ==== {:?} {:?}", field.heders(), field.content_type());
+
+ Either::A(
+ // Field in turn is a stream of *Bytes* objects
+ field.map(|chunk| {
+ println!("-- CHUNK: \n{}",
+ std::str::from_utf8(&chunk).unwrap());})
+ .fold((), |_, _| result(Ok(()))))
+ },
+ multipart::MultipartItem::Nested(mp) => {
+ // Or item could be nested Multipart stream
+ Either::B(result(Ok(())))
+ }
+ }
+ })
+}
+```
+
+Full example is available in
+[examples directory](https://github.com/actix/actix-web/tree/master/examples/multipart/).
+
+## Urlencoded body
+
+Actix provides support for *application/x-www-form-urlencoded* encoded body.
+`HttpResponse::urlencoded()` method returns
+[*UrlEncoded*](../actix_web/dev/struct.UrlEncoded.html) future, it resolves
+into `HashMap` which contains decoded parameters.
+*UrlEncoded* future can resolve into a error in several cases:
+
+* content type is not `application/x-www-form-urlencoded`
+* transfer encoding is `chunked`.
+* content-length is greater than 256k
+* payload terminates with error.
+
+
+```rust
+# extern crate actix_web;
+# extern crate futures;
+use actix_web::*;
+use futures::future::{Future, ok};
+
+fn index(mut req: HttpRequest) -> Box> {
+ req.urlencoded() // <- get UrlEncoded future
+ .from_err()
+ .and_then(|params| { // <- url encoded parameters
+ println!("==== BODY ==== {:?}", params);
+ ok(httpcodes::HTTPOk.into())
+ })
+ .responder()
+}
+# fn main() {}
+```
+
+
+## Streaming request
+
+Actix uses [*Payload*](../actix_web/payload/struct.Payload.html) object as request payload stream.
+*HttpRequest* provides several methods, which can be used for payload access.
+At the same time *Payload* implements *Stream* trait, so it could be used with various
+stream combinators. Also *Payload* provides serveral convinience methods that return
+future object that resolve to Bytes object.
+
+* *readany()* method returns *Stream* of *Bytes* objects.
+
+* *readexactly()* method returns *Future* that resolves when specified number of bytes
+ get received.
+
+* *readline()* method returns *Future* that resolves when `\n` get received.
+
+* *readuntil()* method returns *Future* that resolves when specified bytes string
+ matches in input bytes stream
+
+In this example handle reads request payload chunk by chunk and prints every chunk.
+
+```rust
+# extern crate actix_web;
+# extern crate futures;
+# use futures::future::result;
+use actix_web::*;
+use futures::{Future, Stream};
+
+
+fn index(mut req: HttpRequest) -> Box> {
+ req.payload_mut()
+ .readany()
+ .from_err()
+ .fold((), |_, chunk| {
+ println!("Chunk: {:?}", chunk);
+ result::<_, error::PayloadError>(Ok(()))
+ })
+ .map(|_| HttpResponse::Ok().finish().unwrap())
+ .responder()
+}
+# fn main() {}
+```
diff --git a/guide/src/qs_8.md b/guide/src/qs_8.md
index 465fa3626..53713a205 100644
--- a/guide/src/qs_8.md
+++ b/guide/src/qs_8.md
@@ -1 +1,97 @@
-# Response
+# Testing
+
+Every application should be well tested and. Actix provides the tools to perform unit and
+integration tests.
+
+## Unit tests
+
+For unit testing actix provides request builder type and simple handler runner.
+[*TestRequest*](../actix_web/test/struct.TestRequest.html) implements builder-like pattern.
+You can generate `HttpRequest` instance with `finish()` method or you can
+run your handler with `run()` or `run_async()` methods.
+
+```rust
+# extern crate http;
+# extern crate actix_web;
+use http::{header, StatusCode};
+use actix_web::*;
+use actix_web::test::TestRequest;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
+ if let Ok(s) = hdr.to_str() {
+ return httpcodes::HTTPOk.into()
+ }
+ }
+ httpcodes::HTTPBadRequest.into()
+}
+
+fn main() {
+ let resp = TestRequest::with_header("content-type", "text/plain")
+ .run(index)
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let resp = TestRequest::default()
+ .run(index)
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+```
+
+
+## Integration tests
+
+There are several methods how you can test your application. Actix provides
+[*TestServer*](../actix_web/test/struct.TestServer.html)
+server that could be used to run whole application of just specific handlers
+in real http server. At the moment it is required to use third-party libraries
+to make actual requests, libraries like [reqwest](https://crates.io/crates/reqwest).
+
+In simple form *TestServer* could be configured to use handler. *TestServer::new* method
+accepts configuration function, only argument for this function is *test application*
+instance. You can check [api documentation](../actix_web/test/struct.TestApp.html)
+for more information.
+
+```rust
+# extern crate actix_web;
+extern crate reqwest;
+use actix_web::*;
+use actix_web::test::TestServer;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ httpcodes::HTTPOk.into()
+}
+
+fn main() {
+ let srv = TestServer::new(|app| app.handler(index)); // <- Start new test server
+ let url = srv.url("/"); // <- get handler url
+ assert!(reqwest::get(&url).unwrap().status().is_success()); // <- make request
+}
+```
+
+Other option is to use application factory. In this case you need to pass factory function
+same as you use for real http server configuration.
+
+```rust
+# extern crate actix_web;
+extern crate reqwest;
+use actix_web::*;
+use actix_web::test::TestServer;
+
+fn index(req: HttpRequest) -> HttpResponse {
+ httpcodes::HTTPOk.into()
+}
+
+/// This function get called by http server.
+fn create_app() -> Application {
+ Application::new()
+ .resource("/test", |r| r.h(index))
+}
+
+fn main() {
+ let srv = TestServer::with_factory(create_app); // <- Start new test server
+ let url = srv.url("/test"); // <- get handler url
+ assert!(reqwest::get(&url).unwrap().status().is_success()); // <- make request
+}
+```
diff --git a/guide/src/qs_9.md b/guide/src/qs_9.md
index 7627a1570..9c45fbd04 100644
--- a/guide/src/qs_9.md
+++ b/guide/src/qs_9.md
@@ -1 +1,48 @@
# WebSockets
+
+Actix supports WebSockets out-of-the-box. It is possible to convert request's `Payload`
+to a stream of [*ws::Message*](../actix_web/ws/enum.Message.html) with
+a [*ws::WsStream*](../actix_web/ws/struct.WsStream.html) and then use stream
+combinators to handle actual messages. But it is simplier to handle websocket communications
+with http actor.
+
+```rust
+extern crate actix;
+extern crate actix_web;
+
+use actix::*;
+use actix_web::*;
+
+/// Define http actor
+struct Ws;
+
+impl Actor for Ws {
+ type Context = HttpContext;
+}
+
+/// Define Handler for ws::Message message
+impl Handler for Ws {
+ type Result=();
+
+ fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext) {
+ match msg {
+ ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg),
+ ws::Message::Text(text) => ws::WsWriter::text(ctx, &text),
+ ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin),
+ _ => (),
+ }
+ }
+}
+
+fn main() {
+ Application::new()
+ .resource("/ws/", |r| r.f(|req| ws::start(req, Ws))) // <- register websocket route
+ .finish();
+}
+```
+
+Simple websocket echo server example is available in
+[examples directory](https://github.com/actix/actix-web/blob/master/examples/websocket.rs).
+
+Example chat server with ability to chat over websocket connection or tcp connection
+is available in [websocket-chat directory](https://github.com/actix/actix-web/tree/master/examples/websocket-chat/)
diff --git a/src/application.rs b/src/application.rs
index 4fe5f1dd8..1e4d8273c 100644
--- a/src/application.rs
+++ b/src/application.rs
@@ -1,113 +1,195 @@
+use std::mem;
use std::rc::Rc;
+use std::cell::RefCell;
use std::collections::HashMap;
-use futures::Future;
-use error::Error;
-use route::{RouteHandler, Reply, Handler, WrapHandler, AsyncHandler};
+use handler::Reply;
+use router::{Router, Pattern};
use resource::Resource;
-use recognizer::{RouteRecognizer, check_pattern};
+use handler::{Handler, RouteHandler, WrapHandler};
use httprequest::HttpRequest;
-use httpresponse::HttpResponse;
-use channel::HttpHandler;
-use pipeline::Pipeline;
-use middlewares::Middleware;
-
+use channel::{HttpHandler, IntoHttpHandler, HttpHandlerTask};
+use pipeline::{Pipeline, PipelineHandler};
+use middleware::Middleware;
+use server::ServerSettings;
/// Application
-pub struct Application {
+pub struct HttpApplication {
state: Rc,
prefix: String,
- default: Resource,
- handlers: HashMap>>,
- router: RouteRecognizer>,
- middlewares: Rc>>,
+ router: Router,
+ inner: Rc>>,
+ middlewares: Rc>>>,
}
-impl Application {
+pub(crate) struct Inner {
+ prefix: usize,
+ default: Resource,
+ router: Router,
+ resources: Vec>,
+ handlers: Vec<(String, Box>)>,
+}
- fn run(&self, req: HttpRequest) -> Reply {
- let mut req = req.with_state(Rc::clone(&self.state));
+impl PipelineHandler for Inner {
- if let Some((params, h)) = self.router.recognize(req.path()) {
- if let Some(params) = params {
- req.set_match_info(params);
- }
- h.handle(req)
+ fn handle(&mut self, mut req: HttpRequest) -> Reply {
+ if let Some(idx) = self.router.recognize(&mut req) {
+ self.resources[idx].handle(req.clone(), Some(&mut self.default))
} else {
- for (prefix, handler) in &self.handlers {
- if req.path().starts_with(prefix) {
- req.set_prefix(prefix.len());
+ for &mut (ref prefix, ref mut handler) in &mut self.handlers {
+ let m = {
+ let path = &req.path()[self.prefix..];
+ path.starts_with(prefix) && (path.len() == prefix.len() ||
+ path.split_at(prefix.len()).1.starts_with('/'))
+ };
+ if m {
+ let path: &'static str = unsafe{
+ mem::transmute(&req.path()[self.prefix+prefix.len()..])};
+ if path.is_empty() {
+ req.match_info_mut().add("tail", "");
+ } else {
+ req.match_info_mut().add("tail", path.split_at(1).1);
+ }
return handler.handle(req)
}
}
- self.default.handle(req)
+ self.default.handle(req, None)
}
}
}
-impl HttpHandler for Application {
+#[cfg(test)]
+impl HttpApplication {
+ pub(crate) fn run(&mut self, req: HttpRequest) -> Reply {
+ self.inner.borrow_mut().handle(req)
+ }
+ pub(crate) fn prepare_request(&self, req: HttpRequest) -> HttpRequest {
+ req.with_state(Rc::clone(&self.state), self.router.clone())
+ }
+}
- fn handle(&self, req: HttpRequest) -> Result {
- if req.path().starts_with(&self.prefix) {
- Ok(Pipeline::new(req, Rc::clone(&self.middlewares),
- &|req: HttpRequest| self.run(req)))
+impl HttpHandler for HttpApplication {
+
+ fn handle(&mut self, req: HttpRequest) -> Result, HttpRequest> {
+ let m = {
+ let path = req.path();
+ path.starts_with(&self.prefix) && (
+ path.len() == self.prefix.len() ||
+ path.split_at(self.prefix.len()).1.starts_with('/'))
+ };
+ if m {
+ let inner = Rc::clone(&self.inner);
+ let req = req.with_state(Rc::clone(&self.state), self.router.clone());
+
+ Ok(Box::new(Pipeline::new(req, Rc::clone(&self.middlewares), inner)))
} else {
Err(req)
}
}
}
+struct ApplicationParts {
+ state: S,
+ prefix: String,
+ settings: ServerSettings,
+ default: Resource,
+ resources: HashMap>>,
+ handlers: Vec<(String, Box>)>,
+ external: HashMap,
+ middlewares: Vec>>,
+}
+
+/// Structure that follows the builder pattern for building `Application` structs.
+pub struct Application {
+ parts: Option>,
+}
+
impl Application<()> {
- /// Create default `ApplicationBuilder` with no state
- pub fn default>(prefix: T) -> ApplicationBuilder<()> {
- ApplicationBuilder {
- parts: Some(ApplicationBuilderParts {
+ /// Create application with empty state. Application can
+ /// be configured with builder-like pattern.
+ pub fn new() -> Application<()> {
+ Application {
+ parts: Some(ApplicationParts {
state: (),
- prefix: prefix.into(),
+ prefix: "/".to_owned(),
+ settings: ServerSettings::default(),
default: Resource::default_not_found(),
- handlers: HashMap::new(),
resources: HashMap::new(),
+ handlers: Vec::new(),
+ external: HashMap::new(),
middlewares: Vec::new(),
})
}
}
}
+impl Default for Application<()> {
+ fn default() -> Self {
+ Application::new()
+ }
+}
+
impl Application where S: 'static {
- /// Create application builder with specific state. State is shared with all
- /// routes within same application and could be
- /// accessed with `HttpContext::state()` method.
- pub fn build>(prefix: T, state: S) -> ApplicationBuilder {
- ApplicationBuilder {
- parts: Some(ApplicationBuilderParts {
+ /// Create application with specific state. Application can be
+ /// configured with builder-like pattern.
+ ///
+ /// State is shared with all reousrces within same application and could be
+ /// accessed with `HttpRequest::state()` method.
+ pub fn with_state(state: S) -> Application {
+ Application {
+ parts: Some(ApplicationParts {
state: state,
- prefix: prefix.into(),
+ prefix: "/".to_owned(),
+ settings: ServerSettings::default(),
default: Resource::default_not_found(),
- handlers: HashMap::new(),
resources: HashMap::new(),
+ handlers: Vec::new(),
+ external: HashMap::new(),
middlewares: Vec::new(),
})
}
}
-}
-struct ApplicationBuilderParts {
- state: S,
- prefix: String,
- default: Resource,
- handlers: HashMap>>,
- resources: HashMap>,
- middlewares: Vec>,
-}
-
-/// Structure that follows the builder pattern for building `Application` structs.
-pub struct ApplicationBuilder {
- parts: Option>,
-}
-
-impl ApplicationBuilder where S: 'static {
+ /// Set application prefix
+ ///
+ /// Only requests that matches application's prefix get processed by this application.
+ /// Application prefix always contains laading "/" slash. If supplied prefix
+ /// does not contain leading slash, it get inserted. Prefix should
+ /// consists valid path segments. i.e for application with
+ /// prefix `/app` any request with following paths `/app`, `/app/` or `/app/test`
+ /// would match, but path `/application` would not match.
+ ///
+ /// In the following example only requests with "/app/" path prefix
+ /// get handled. Request with path "/app/test/" would be handled,
+ /// but request with path "/application" or "/other/..." would return *NOT FOUND*
+ ///
+ /// ```rust
+ /// # extern crate actix_web;
+ /// use actix_web::*;
+ ///
+ /// fn main() {
+ /// let app = Application::new()
+ /// .prefix("/app")
+ /// .resource("/test", |r| {
+ /// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
+ /// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
+ /// })
+ /// .finish();
+ /// }
+ /// ```
+ pub fn prefix>(mut self, prefix: P) -> Application {
+ {
+ let parts = self.parts.as_mut().expect("Use after finish");
+ let mut prefix = prefix.into();
+ if !prefix.starts_with('/') {
+ prefix.insert(0, '/')
+ }
+ parts.prefix = prefix;
+ }
+ self
+ }
/// Configure resource for specific path.
///
@@ -118,7 +200,7 @@ impl ApplicationBuilder where S: 'static {
/// A variable part is specified in the form `{identifier}`, where
/// the identifier can be used later in a request handler to access the matched
/// value for that part. This is done by looking up the identifier
- /// in the `Params` object returned by `Request.match_info()` method.
+ /// in the `Params` object returned by `HttpRequest.match_info()` method.
///
/// By default, each part matches the regular expression `[^{}/]+`.
///
@@ -128,37 +210,39 @@ impl ApplicationBuilder where S: 'static {
/// store userid and friend in the exposed Params object:
///
/// ```rust
- /// extern crate actix_web;
+ /// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
- /// let app = Application::default("/")
+ /// let app = Application::new()
/// .resource("/test", |r| {
- /// r.get(|req| httpcodes::HTTPOk);
- /// r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
- /// })
- /// .finish();
+ /// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
+ /// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
+ /// });
/// }
/// ```
- pub fn resource>(&mut self, path: P, f: F) -> &mut Self
+ pub fn resource(mut self, path: &str, f: F) -> Application
where F: FnOnce(&mut Resource) + 'static
{
{
let parts = self.parts.as_mut().expect("Use after finish");
// add resource
- let path = path.into();
- if !parts.resources.contains_key(&path) {
- check_pattern(&path);
- parts.resources.insert(path.clone(), Resource::default());
+ let mut resource = Resource::default();
+ f(&mut resource);
+
+ let pattern = Pattern::new(resource.get_name(), path, "^/");
+ if parts.resources.contains_key(&pattern) {
+ panic!("Resource {:?} is registered.", path);
}
- f(parts.resources.get_mut(&path).unwrap());
+
+ parts.resources.insert(pattern, Some(resource));
}
self
}
- /// Default resource is used if no match route could be found.
- pub fn default_resource(&mut self, f: F) -> &mut Self
+ /// Default resource is used if no matched route could be found.
+ pub fn default_resource(mut self, f: F) -> Application
where F: FnOnce(&mut Resource) + 'static
{
{
@@ -168,105 +252,142 @@ impl ApplicationBuilder where S: 'static {
self
}
- /// This method register handler for specified path prefix.
- /// Any path that starts with this prefix matches handler.
+ /// Register external resource.
+ ///
+ /// External resources are useful for URL generation purposes only and
+ /// are never considered for matching at request time.
+ /// Call to `HttpRequest::url_for()` will work as expected.
///
/// ```rust
- /// extern crate actix_web;
+ /// # extern crate actix_web;
/// use actix_web::*;
///
+ /// fn index(mut req: HttpRequest) -> Result {
+ /// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
+ /// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
+ /// Ok(httpcodes::HTTPOk.into())
+ /// }
+ ///
/// fn main() {
- /// let app = Application::default("/")
- /// .handler("/test", |req| {
- /// match *req.method() {
- /// Method::GET => httpcodes::HTTPOk,
- /// Method::POST => httpcodes::HTTPMethodNotAllowed,
- /// _ => httpcodes::HTTPNotFound,
- /// }
- /// })
+ /// let app = Application::new()
+ /// .resource("/index.html", |r| r.f(index))
+ /// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .finish();
/// }
/// ```
- pub fn handler(&mut self, path: P, handler: F) -> &mut Self
- where P: Into,
- F: Fn(HttpRequest) -> R + 'static,
- R: Into + 'static
+ pub fn external_resource(mut self, name: T, url: U) -> Application
+ where T: AsRef, U: AsRef
{
- self.parts.as_mut().expect("Use after finish")
- .handlers.insert(path.into(), Box::new(WrapHandler::new(handler)));
+ {
+ let parts = self.parts.as_mut().expect("Use after finish");
+
+ if parts.external.contains_key(name.as_ref()) {
+ panic!("External resource {:?} is registered.", name.as_ref());
+ }
+ parts.external.insert(
+ String::from(name.as_ref()), Pattern::new(name.as_ref(), url.as_ref(), "^/"));
+ }
self
}
- /// This method register handler for specified path prefix.
- /// Any path that starts with this prefix matches handler.
- pub fn route(&mut self, path: P, handler: H) -> &mut Self
- where P: Into, H: Handler
+ /// Configure handler for specific path prefix.
+ ///
+ /// Path prefix consists valid path segments. i.e for prefix `/app`
+ /// any request with following paths `/app`, `/app/` or `/app/test`
+ /// would match, but path `/application` would not match.
+ ///
+ /// ```rust
+ /// # extern crate actix_web;
+ /// use actix_web::*;
+ ///
+ /// fn main() {
+ /// let app = Application::new()
+ /// .handler("/app", |req: HttpRequest| {
+ /// match *req.method() {
+ /// Method::GET => httpcodes::HTTPOk,
+ /// Method::POST => httpcodes::HTTPMethodNotAllowed,
+ /// _ => httpcodes::HTTPNotFound,
+ /// }});
+ /// }
+ /// ```
+ pub fn handler>(mut self, path: &str, handler: H) -> Application
{
- self.parts.as_mut().expect("Use after finish")
- .handlers.insert(path.into(), Box::new(WrapHandler::new(handler)));
+ {
+ let path = path.trim().trim_right_matches('/').to_owned();
+ let parts = self.parts.as_mut().expect("Use after finish");
+ parts.handlers.push((path, Box::new(WrapHandler::new(handler))));
+ }
self
}
- /// This method register async handler for specified path prefix.
- /// Any path that starts with this prefix matches handler.
- pub fn async(&mut self, path: P, handler: F) -> &mut Self
- where F: Fn(HttpRequest) -> R + 'static,
- R: Future- + 'static,
- P: Into,
- {
- self.parts.as_mut().expect("Use after finish")
- .handlers.insert(path.into(), Box::new(AsyncHandler::new(handler)));
- self
- }
-
- /// Construct application
- pub fn middleware(&mut self, mw: T) -> &mut Self
- where T: Middleware + 'static
+ /// Register a middleware
+ pub fn middleware(mut self, mw: T) -> Application
+ where T: Middleware + 'static
{
self.parts.as_mut().expect("Use after finish")
.middlewares.push(Box::new(mw));
self
}
- /// Construct application
- pub fn finish(&mut self) -> Application {
+ /// Finish application configuration and create HttpHandler object
+ pub fn finish(&mut self) -> HttpApplication {
let parts = self.parts.take().expect("Use after finish");
+ let prefix = parts.prefix.trim().trim_right_matches('/');
- let mut handlers = HashMap::new();
- let prefix = if parts.prefix.ends_with('/') {
- parts.prefix
- } else {
- parts.prefix + "/"
- };
-
- let mut routes = Vec::new();
- for (path, handler) in parts.resources {
- routes.push((path, handler))
+ let mut resources = parts.resources;
+ for (_, pattern) in parts.external {
+ resources.insert(pattern, None);
}
- for (path, mut handler) in parts.handlers {
- let path = prefix.clone() + path.trim_left_matches('/');
- handlers.insert(path, handler);
- }
- Application {
+ let (router, resources) = Router::new(prefix, parts.settings, resources);
+
+ let inner = Rc::new(RefCell::new(
+ Inner {
+ prefix: prefix.len(),
+ default: parts.default,
+ router: router.clone(),
+ resources: resources,
+ handlers: parts.handlers,
+ }
+ ));
+
+ HttpApplication {
state: Rc::new(parts.state),
- prefix: prefix.clone(),
- default: parts.default,
- handlers: handlers,
- router: RouteRecognizer::new(prefix, routes),
+ prefix: prefix.to_owned(),
+ inner: inner,
+ router: router.clone(),
middlewares: Rc::new(parts.middlewares),
}
}
}
-impl From> for Application {
- fn from(mut builder: ApplicationBuilder) -> Application {
- builder.finish()
+impl IntoHttpHandler for Application