Skip to content

Commit c563d64

Browse files
committed
add support for upgrades
1 parent 66b887d commit c563d64

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ edition = "2018"
1414
[dependencies]
1515
httparse = "1.3.3"
1616
async-std = { version = "1.6.0", features = ["unstable"] }
17-
http-types = "2.0.0"
17+
http-types = { version = "2.0.0", features = ["unstable"] }
1818
byte-pool = "0.2.1"
1919
lazy_static = "1.4.0"
2020
futures-core = "0.3.1"

src/server/mod.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
use std::time::Duration;
44

55
use async_std::future::{timeout, Future, TimeoutError};
6-
use async_std::io::{self};
7-
use async_std::io::{Read, Write};
8-
use http_types::{Request, Response};
6+
use async_std::io::{self, Read, Write};
7+
use http_types::headers::{CONNECTION, UPGRADE};
8+
use http_types::upgrade::Connection;
9+
use http_types::{Request, Response, StatusCode};
910

1011
mod decode;
1112
mod encode;
@@ -70,14 +71,32 @@ where
7071
}
7172
};
7273

74+
let upgrade_requested = match (req.header(UPGRADE), req.header(CONNECTION)) {
75+
(Some(_), Some(upgrade)) if upgrade.as_str().eq_ignore_ascii_case("upgrade") => true,
76+
_ => false,
77+
};
78+
7379
let method = req.method();
80+
7481
// Pass the request to the endpoint and encode the response.
75-
let res = endpoint(req).await?;
82+
let mut res = endpoint(req).await?;
83+
84+
let upgrade_provided = res.status() == StatusCode::SwitchingProtocols && res.has_upgrade();
85+
86+
let upgrade_sender = if upgrade_requested && upgrade_provided {
87+
Some(res.send_upgrade())
88+
} else {
89+
None
90+
};
7691

7792
let mut encoder = Encoder::new(res, method);
7893

7994
// Stream the response to the writer.
8095
io::copy(&mut encoder, &mut io).await?;
96+
97+
if let Some(upgrade_sender) = upgrade_sender {
98+
upgrade_sender.send(Connection::new(io.clone())).await;
99+
}
81100
}
82101

83102
Ok(())

0 commit comments

Comments
 (0)