Skip to content

Commit 4e9a006

Browse files
authored
docs(example): support requests to domain names in example http_proxy (#2513)
1 parent 963dc23 commit 4e9a006

File tree

1 file changed

+12
-27
lines changed

1 file changed

+12
-27
lines changed

examples/http_proxy.rs

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
use std::convert::Infallible;
44
use std::net::SocketAddr;
55

6-
use futures_util::future::try_join;
7-
86
use hyper::service::{make_service_fn, service_fn};
97
use hyper::upgrade::Upgraded;
108
use hyper::{Body, Client, Method, Request, Response, Server};
@@ -18,8 +16,8 @@ type HttpClient = Client<hyper::client::HttpConnector>;
1816
// 2. config http_proxy in command line
1917
// $ export http_proxy=http://127.0.0.1:8100
2018
// $ export https_proxy=http://127.0.0.1:8100
21-
// 3. send requests (don't use a domain name)
22-
// $ curl -i https://8.8.8.8
19+
// 3. send requests
20+
// $ curl -i https://www.some_domain.com/
2321
#[tokio::main]
2422
async fn main() {
2523
let addr = SocketAddr::from(([127, 0, 0, 1], 8100));
@@ -88,38 +86,25 @@ async fn proxy(client: HttpClient, req: Request<Body>) -> Result<Response<Body>,
8886
}
8987
}
9088

91-
fn host_addr(uri: &http::Uri) -> Option<SocketAddr> {
92-
uri.authority().and_then(|auth| auth.as_str().parse().ok())
89+
fn host_addr(uri: &http::Uri) -> Option<String> {
90+
uri.authority().and_then(|auth| Some(auth.to_string()))
9391
}
9492

9593
// Create a TCP connection to host:port, build a tunnel between the connection and
9694
// the upgraded connection
97-
async fn tunnel(upgraded: Upgraded, addr: SocketAddr) -> std::io::Result<()> {
95+
async fn tunnel(mut upgraded: Upgraded, addr: String) -> std::io::Result<()> {
9896
// Connect to remote server
9997
let mut server = TcpStream::connect(addr).await?;
10098

10199
// Proxying data
102-
let amounts = {
103-
let (mut server_rd, mut server_wr) = server.split();
104-
let (mut client_rd, mut client_wr) = tokio::io::split(upgraded);
105-
106-
let client_to_server = tokio::io::copy(&mut client_rd, &mut server_wr);
107-
let server_to_client = tokio::io::copy(&mut server_rd, &mut client_wr);
108-
109-
try_join(client_to_server, server_to_client).await
110-
};
100+
let (from_client, from_server) =
101+
tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?;
111102

112103
// Print message when done
113-
match amounts {
114-
Ok((from_client, from_server)) => {
115-
println!(
116-
"client wrote {} bytes and received {} bytes",
117-
from_client, from_server
118-
);
119-
}
120-
Err(e) => {
121-
println!("tunnel error: {}", e);
122-
}
123-
};
104+
println!(
105+
"client wrote {} bytes and received {} bytes",
106+
from_client, from_server
107+
);
108+
124109
Ok(())
125110
}

0 commit comments

Comments
 (0)