1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-12-01 11:00:06 +01:00
actix-web/examples/http-proxy/src/main.rs

58 lines
2.2 KiB
Rust
Raw Normal View History

2018-03-05 20:12:19 +01:00
extern crate actix;
extern crate actix_web;
extern crate futures;
extern crate env_logger;
use futures::{Future, Stream};
2018-03-31 03:54:38 +02:00
use actix_web::{client, server, middleware,
2018-03-31 09:16:55 +02:00
App, AsyncResponder, Body,
2018-03-31 03:54:38 +02:00
HttpRequest, HttpResponse, HttpMessage, Error};
2018-03-05 20:12:19 +01:00
/// Stream client request response and then send body to a server response
2018-03-05 20:12:19 +01:00
fn index(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
client::ClientRequest::get("https://www.rust-lang.org/en-US/")
.finish().unwrap()
.send()
2018-03-31 03:54:38 +02:00
.map_err(Error::from) // <- convert SendRequestError to an Error
.and_then(
|resp| resp.body() // <- this is MessageBody type, resolves to complete body
2018-03-24 07:35:52 +01:00
.from_err() // <- convert PayloadError to a Error
.and_then(|body| { // <- we got complete body, now send as server response
2018-03-31 08:37:15 +02:00
Ok(HttpResponse::Ok().body(body))
2018-03-05 20:12:19 +01:00
}))
.responder()
}
/// streaming client request to a streaming server response
fn streaming(_req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
// send client request
client::ClientRequest::get("https://www.rust-lang.org/en-US/")
.finish().unwrap()
.send() // <- connect to host and send request
2018-03-31 03:54:38 +02:00
.map_err(Error::from) // <- convert SendRequestError to an Error
.and_then(|resp| { // <- we received client response
2018-03-31 08:37:15 +02:00
Ok(HttpResponse::Ok()
// read one chunk from client response and send this chunk to a server response
// .from_err() converts PayloadError to a Error
.body(Body::Streaming(Box::new(resp.from_err()))))
2018-03-05 20:12:19 +01:00
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let sys = actix::System::new("http-proxy");
2018-03-05 20:12:19 +01:00
2018-03-31 03:54:38 +02:00
let _addr = server::new(
2018-03-31 09:16:55 +02:00
|| App::new()
2018-03-05 20:12:19 +01:00
.middleware(middleware::Logger::default())
.resource("/streaming", |r| r.f(streaming))
2018-03-05 20:12:19 +01:00
.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();
}