3
3
use std:: convert:: Infallible ;
4
4
use std:: net:: SocketAddr ;
5
5
6
- use futures_util:: future:: try_join;
7
-
8
6
use hyper:: service:: { make_service_fn, service_fn} ;
9
7
use hyper:: upgrade:: Upgraded ;
10
8
use hyper:: { Body , Client , Method , Request , Response , Server } ;
@@ -18,8 +16,8 @@ type HttpClient = Client<hyper::client::HttpConnector>;
18
16
// 2. config http_proxy in command line
19
17
// $ export http_proxy=http://127.0.0.1:8100
20
18
// $ 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/
23
21
#[ tokio:: main]
24
22
async fn main ( ) {
25
23
let addr = SocketAddr :: from ( ( [ 127 , 0 , 0 , 1 ] , 8100 ) ) ;
@@ -88,38 +86,25 @@ async fn proxy(client: HttpClient, req: Request<Body>) -> Result<Response<Body>,
88
86
}
89
87
}
90
88
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 ( ) ) )
93
91
}
94
92
95
93
// Create a TCP connection to host:port, build a tunnel between the connection and
96
94
// 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 < ( ) > {
98
96
// Connect to remote server
99
97
let mut server = TcpStream :: connect ( addr) . await ?;
100
98
101
99
// 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 ?;
111
102
112
103
// 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
+
124
109
Ok ( ( ) )
125
110
}
0 commit comments