Skip to content

Instantly share code, notes, and snippets.

@BillBarnhill
Last active March 19, 2021 10:25
Show Gist options
  • Save BillBarnhill/cb46b73e369842baf9cdd669eb2c3cb9 to your computer and use it in GitHub Desktop.
Save BillBarnhill/cb46b73e369842baf9cdd669eb2c3cb9 to your computer and use it in GitHub Desktop.
Main.rs with problem with signature of on_ws_request
// This version compiles, and works
#[macro_use]
extern crate serde_derive;
use serde_json::{Map, Value};
use tide_websockets::{
WebSocket,
Message
};
use async_std::stream::StreamExt;
use std::sync::{
Arc
};
use async_std::sync::{
RwLock
};
use std::collections::HashMap;
const _DEFAULT_4XX_BODY: &[u8] = b"Oops! I can't find what you're looking for..." as &[_];
const _DEFAULT_5XX_BODY: &[u8] = b"I'm broken, apparently." as &[_];
#[derive(Deserialize, Serialize, Debug, Clone)]
struct Vote {
uid: String,
card: String
}
#[derive(Clone,Debug)]
struct State {
votes: Arc<RwLock<HashMap<String,Vote>>>
}
fn start_msg() -> Map<String, Value> {
let mut map = Map::new();
map.insert("Bool Example".to_string(), false.into());
map.insert("String Example".to_string(), "Str".to_string().into());
map.insert("Number Example".to_string(), 2.into());
map
}
async fn on_ws_request(req : tide::Request<State>, mut stream : tide_websockets::WebSocketConnection)
-> std::result::Result<(), tide::Error> {
tide::log::info!("Got a WebSocket connection");
stream.send_json(&start_msg()).await.unwrap();
tide::log::info!("Sent start message");
let mut votes = req.state().votes.write().await;
loop {
for (k, v) in votes.iter() {
tide::log::info!("{:?}: \"{:?}\"", k, v);
}
let raw = stream.next().await.unwrap();
tide::log::info!("State: {:?}", req.state());
tide::log::info!("Received raw-> {:?}\n", &raw);
if let Ok(Message::Text(msg)) = raw {
tide::log::info!("Received msg-> {:?}\n", &msg);
let vote : Vote = serde_json::from_str(&msg).unwrap();
votes.insert(vote.uid.clone(), vote.clone());
tide::log::info!("Received vote= {:?}", vote);
}
}
}
#[async_std::main]
async fn main() -> std::result::Result<(), std::io::Error> {
tide::log::start();
let mut app = tide::with_state( State { votes: Default::default() });
app.at("/").serve_file("plan.html")?;
app.at("/ws").get(WebSocket::new(on_ws_request));
app.listen("127.0.0.1:8080").await?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment