From ea2a8f6908a78d0e4d34b21bac80feb7f4fd532c Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Mon, 5 Mar 2018 11:12:19 -0800 Subject: [PATCH] add http proxy example --- .travis.yml | 1 + Cargo.toml | 1 + examples/http-proxy/Cargo.toml | 11 ++++++++ examples/http-proxy/src/main.rs | 47 +++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 examples/http-proxy/Cargo.toml create mode 100644 examples/http-proxy/src/main.rs diff --git a/.travis.yml b/.travis.yml index ddaaae14b..640aa1b92 100644 --- a/.travis.yml +++ b/.travis.yml @@ -55,6 +55,7 @@ script: if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then cd examples/basics && cargo check && cd ../.. cd examples/hello-world && cargo check && cd ../.. + cd examples/http-proxy && cargo check && cd ../.. cd examples/multipart && cargo check && cd ../.. cd examples/json && cargo check && cd ../.. cd examples/juniper && cargo check && cd ../.. diff --git a/Cargo.toml b/Cargo.toml index 9387ad6f2..9b69e2560 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,6 +106,7 @@ members = [ "examples/r2d2", "examples/json", "examples/hello-world", + "examples/http-proxy", "examples/multipart", "examples/state", "examples/redis-session", diff --git a/examples/http-proxy/Cargo.toml b/examples/http-proxy/Cargo.toml new file mode 100644 index 000000000..7b9597bff --- /dev/null +++ b/examples/http-proxy/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "http-proxy" +version = "0.1.0" +authors = ["Nikolay Kim "] +workspace = "../.." + +[dependencies] +env_logger = "0.5" +futures = "0.1" +actix = "0.5" +actix-web = { path = "../../", features=["alpn"] } diff --git a/examples/http-proxy/src/main.rs b/examples/http-proxy/src/main.rs new file mode 100644 index 000000000..52416d4ac --- /dev/null +++ b/examples/http-proxy/src/main.rs @@ -0,0 +1,47 @@ +extern crate actix; +extern crate actix_web; +extern crate futures; +extern crate env_logger; + +use actix_web::*; +use futures::Future; +use futures::future::{ok, err, Either}; + + +fn index(_req: HttpRequest) -> Box> { + client::ClientRequest::get("https://www.rust-lang.org/en-US/") + .finish().unwrap() + .send() + .map_err(|e| error::Error::from(error::ErrorInternalServerError(e))) + .then(|result| match result { + Ok(resp) => { + Either::A(resp.body().from_err().and_then(|body| { + match httpcodes::HttpOk.build().body(body) { + Ok(resp) => ok(resp), + Err(e) => err(e.into()), + } + })) + }, + Err(e) => { + Either::B(err(error::Error::from(e))) + } + }) + .responder() +} + +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("/", |r| r.f(index))) + .bind("127.0.0.1:8080").unwrap() + .start(); + + println!("Started http server: 127.0.0.1:8080"); + let _ = sys.run(); +}