1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/http-proxy/src/main.rs

53 lines
1.9 KiB
Rust
Raw Normal View History

2019-03-27 07:33:13 +01:00
use actix_web::client::Client;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use futures::Future;
/// Stream client request response and then send body to a server response
2019-03-27 07:33:13 +01:00
fn index(client: web::Data<Client>) -> impl Future<Item = HttpResponse, Error = Error> {
client
.get("http://127.0.0.1:8081/")
.send()
2019-03-10 03:03:09 +01:00
.map_err(Error::from) // <- convert SendRequestError to an Error
2019-04-04 20:37:14 +02:00
.and_then(|mut resp| {
2019-03-10 03:03:09 +01:00
resp.body() // <- this is MessageBody type, resolves to complete body
.from_err() // <- convert PayloadError to an Error
.and_then(|body| {
// <- we got complete body, now send as server response
Ok(HttpResponse::Ok().body(body))
2019-03-10 03:03:09 +01:00
})
})
}
/// streaming client request to a streaming server response
2019-03-27 07:33:13 +01:00
fn streaming(
client: web::Data<Client>,
) -> impl Future<Item = HttpResponse, Error = impl Into<Error>> {
// send client request
2019-03-27 07:33:13 +01:00
client
2019-06-10 18:06:56 +02:00
.get("https://www.rust-lang.org/")
2019-03-10 03:03:09 +01:00
.send() // <- connect to host and send request
.map_err(Error::from) // <- convert SendRequestError to an Error
.and_then(|resp| {
// <- we received client response
Ok(HttpResponse::Ok()
2019-03-10 03:03:09 +01:00
// read one chunk from client response and send this chunk to a server response
// .from_err() converts PayloadError to an Error
2019-03-27 07:33:13 +01:00
.streaming(resp))
})
}
2019-03-27 07:33:13 +01:00
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=trace");
env_logger::init();
2019-03-27 07:33:13 +01:00
HttpServer::new(|| {
App::new()
2019-03-27 07:33:13 +01:00
.data(Client::new())
.wrap(middleware::Logger::default())
.service(web::resource("/streaming").to_async(streaming))
.service(web::resource("/").to_async(index))
2019-03-10 03:03:09 +01:00
})
2019-03-27 07:33:13 +01:00
.bind("127.0.0.1:8080")?
.run()
}