Skip to content

Commit

Permalink
Simplify response body type in server-custom-accept example
Browse files Browse the repository at this point in the history
The empty `Full<T>::default()` body behaves like the `Empty` implementation.
  • Loading branch information
nickelc authored and sdroege committed Dec 31, 2023
1 parent dcedd5c commit 30a1f78
Showing 1 changed file with 4 additions and 19 deletions.
23 changes: 4 additions & 19 deletions examples/server-custom-accept.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,7 @@ use tungstenite::{

type Tx = UnboundedSender<Message>;
type PeerMap = Arc<Mutex<HashMap<SocketAddr, Tx>>>;

/// Helper methods to create responses
mod body {
use http_body_util::{Either, Empty, Full};
use hyper::body::Bytes;

pub type Body = Either<Empty<Bytes>, Full<Bytes>>;

pub fn empty() -> Body {
Either::Left(Empty::new())
}

pub fn bytes<B: Into<Bytes>>(chunk: B) -> Body {
Either::Right(Full::from(chunk.into()))
}
}
type Body = http_body_util::Full<hyper::body::Bytes>;

async fn handle_connection(
peer_map: PeerMap,
Expand Down Expand Up @@ -114,7 +99,7 @@ async fn handle_request(
peer_map: PeerMap,
mut req: Request<Incoming>,
addr: SocketAddr,
) -> Result<Response<body::Body>, Infallible> {
) -> Result<Response<Body>, Infallible> {
println!("Received a new, potentially ws handshake");
println!("The request's path is: {}", req.uri().path());
println!("The request's headers are:");
Expand Down Expand Up @@ -148,7 +133,7 @@ async fn handle_request(
|| key.is_none()
|| req.uri() != "/socket"
{
return Ok(Response::new(body::bytes("Hello World!")));
return Ok(Response::new(Body::from("Hello World!")));
}
let ver = req.version();
tokio::task::spawn(async move {
Expand All @@ -169,7 +154,7 @@ async fn handle_request(
Err(e) => println!("upgrade error: {}", e),
}
});
let mut res = Response::new(body::empty());
let mut res = Response::new(Body::default());
*res.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
*res.version_mut() = ver;
res.headers_mut().append(CONNECTION, upgrade);
Expand Down

0 comments on commit 30a1f78

Please sign in to comment.