Skip to content

Commit c63fdac

Browse files
committed
server optimization
1 parent 577ed05 commit c63fdac

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/server.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::collections::HashMap;
22
use tokio::io;
33
use tokio::io::AsyncWriteExt;
44
use tokio::net::{TcpListener, TcpStream};
5+
use tokio::task;
56

67
use futures::FutureExt;
78
use std::error::Error;
@@ -42,17 +43,27 @@ async fn handle(inbound: TcpStream, hosts: HashMap<String, String>) -> Result<()
4243
// buffer init
4344
let mut buf = vec![0; 256];
4445
let mut headers = [httparse::EMPTY_HEADER; 16];
45-
let mut r = httparse::Request::new(&mut headers);
4646

4747
// peek into buffer and parse request
4848
inbound.peek(&mut buf).await?;
49-
r.parse(&buf)?;
5049

51-
// try to parse headers
52-
let p = headers.iter().position(|&h| h.name == "Host").unwrap();
53-
let host = String::from_utf8_lossy(headers[p].value).to_string();
50+
let b = buf.leak();
51+
52+
// do buffer parsing
53+
let host = task::spawn_blocking(move || {
54+
let mut r = httparse::Request::new(&mut headers);
55+
r.parse(b).unwrap();
56+
// try to parse headers
57+
let p = headers.iter().position(|&h| h.name == "Host").unwrap();
58+
let host = String::from_utf8_lossy(headers[p].value).to_string();
59+
host
60+
})
61+
.await?;
62+
63+
// lookup
5464
let to = &hosts[&host];
5565

66+
// spawn proxy
5667
let proxy = proxy(inbound, to.to_string()).map(|r| {
5768
if let Err(e) = r {
5869
log::error!("failed to proxy; {}", e);

0 commit comments

Comments
 (0)