Skip to content

Instantly share code, notes, and snippets.

@tsidea
Created February 1, 2021 19:00
Show Gist options
  • Save tsidea/7b8bec9283e9ea9462df269d8363151c to your computer and use it in GitHub Desktop.
Save tsidea/7b8bec9283e9ea9462df269d8363151c to your computer and use it in GitHub Desktop.
simple http handler
use hyper::header;
...
async fn handle_request(mut request: Request<Body>, remote_addr: SocketAddr) -> Result<Response<Body>, Infallible> {
match (request.uri().path(), request.headers().contains_key(header::UPGRADE)) {
//if the request is ws_echo and the request headers contains an Upgrade key
("/ws_echo", true) => {
//handle websocket HERE
...
//should return websocket response handshake here
Ok::<_, Infallible>(Response::new(Body::empty()))
},
("/ws_echo", false) => {
//handle the case where the url is /ws_echo, but does not have an Upgrade field
Ok(Response::new(Body::from(format!("Getting even warmer, \
try connecting to this url \
using a websocket client.\n"))))
},
(url@_, false) => {
//handle any other url without an Upgrade header field
Ok(Response::new(Body::from(format!("This {} url doesn't do \
much, try accessing the \
/ws_echo url instead.\n", url))))
},
(_, true) => {
//handle any other url with an Upgrade header field
Ok(Response::new(Body::from(format!("Getting warmer, but I'm \
only letting you connect \
via websocket over on \
/ws_echo, try that url.\n"))))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment