Skip to content

Commit 152af75

Browse files
committed
docs(examples): update proxy example to async/await
1 parent 5da17df commit 152af75

File tree

2 files changed

+48
-44
lines changed

2 files changed

+48
-44
lines changed

examples/proxy.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#![feature(async_await)]
2+
#![deny(warnings)]
3+
4+
use hyper::{Client, Error, Server};
5+
use hyper::service::{make_service_fn, service_fn};
6+
use std::net::SocketAddr;
7+
8+
#[hyper::rt::main]
9+
async fn main() {
10+
pretty_env_logger::init();
11+
12+
let in_addr = ([127, 0, 0, 1], 3001).into();
13+
let out_addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
14+
15+
let client_main = Client::new();
16+
17+
let out_addr_clone = out_addr.clone();
18+
19+
// The closure inside `make_service_fn` is run for each connection,
20+
// creating a 'service' to handle requests for that specific connection.
21+
let make_service = make_service_fn(move |_| {
22+
let client = client_main.clone();
23+
24+
async move {
25+
// This is the `Service` that will handle the connection.
26+
// `service_fn` is a helper to convert a function that
27+
// returns a Response into a `Service`.
28+
Ok::<_, Error>(service_fn(move |mut req| {
29+
let uri_string = format!("http://{}/{}",
30+
out_addr_clone,
31+
req.uri().path_and_query().map(|x| x.as_str()).unwrap_or(""));
32+
let uri = uri_string.parse().unwrap();
33+
*req.uri_mut() = uri;
34+
client.request(req)
35+
}))
36+
}
37+
});
38+
39+
let server = Server::bind(&in_addr)
40+
.serve(make_service);
41+
42+
println!("Listening on http://{}", in_addr);
43+
println!("Proxying on http://{}", out_addr);
44+
45+
if let Err(e) = server.await {
46+
eprintln!("server error: {}", e);
47+
}
48+
}

examples_disabled/proxy.rs

Lines changed: 0 additions & 44 deletions
This file was deleted.

0 commit comments

Comments
 (0)