tidy up main.rs

This commit is contained in:
Tangent Wantwight 2020-05-25 18:35:01 -04:00
parent eb7ea021b0
commit 2f64708e4e

View file

@ -1,10 +1,11 @@
#[macro_use] #[macro_use]
extern crate log; extern crate log;
use anyhow::{Context, Error, Result}; use anyhow::{Context, Result};
use future::ok; use future::ready;
use futures::prelude::*; use futures::prelude::*;
use net::{ClientMessage, ServerMessage, server::greet}; use futures::try_join;
use net::{server::greet, ClientMessage, ServerMessage};
use serde_json::{from_str, to_string}; use serde_json::{from_str, to_string};
use std::net::ToSocketAddrs; use std::net::ToSocketAddrs;
use stream::FuturesUnordered; use stream::FuturesUnordered;
@ -29,11 +30,15 @@ async fn main() -> Result<()> {
let args = Args::from_args(); let args = Args::from_args();
// dispatch websockets // dispatch websockets
let socket_handler = ws().map(|upgrade: Ws| upgrade.on_upgrade(|ws| async { let socket_handler = ws().map(|upgrade: Ws| {
upgrade.on_upgrade(|ws| {
async {
if let Err(error) = handle_socket(ws).await { if let Err(error) = handle_socket(ws).await {
warn!("Websocket connection lost: {:#}", error); warn!("Websocket connection lost: {:#}", error);
} }
})); }
})
});
let addrs = args let addrs = args
.listen .listen
@ -54,12 +59,16 @@ async fn handle_socket(websocket: WebSocket) -> Result<()> {
let (sink, mut source) = websocket.split(); let (sink, mut source) = websocket.split();
let mut sink = sink.with(|msg: ServerMessage| { let mut sink = sink.with(|msg: ServerMessage| {
let json = to_string(&msg).expect("JSON encoding shouldn't fail"); ready(
ok::<Message, Error>(Message::text(json)) to_string(&msg)
.context("JSON encoding shouldn't fail")
.map(|json| Message::text(json)),
)
}); });
greet(&mut sink).await?; greet(&mut sink).await?;
let input_task = async {
loop { loop {
match source.next().await { match source.next().await {
Some(Ok(msg)) => match msg.to_str() { Some(Ok(msg)) => match msg.to_str() {
@ -70,8 +79,9 @@ async fn handle_socket(websocket: WebSocket) -> Result<()> {
Err(()) => debug!("Non-text message"), Err(()) => debug!("Non-text message"),
}, },
Some(Err(error)) => return Err(error.into()), Some(Err(error)) => return Err(error.into()),
None => break, None => break Ok(()),
}
} }
}; };
Ok(()) try_join!(input_task).map(|((),)| ())
} }