Skip to content

Commit

Permalink
add websocket example
Browse files Browse the repository at this point in the history
Signed-off-by: Anthony Whalley <anton@venshare.com>
  • Loading branch information
No9 committed May 15, 2021
1 parent a53b6cb commit 205e16a
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 27 deletions.
6 changes: 5 additions & 1 deletion example-projects/tide-example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ cloudevents-sdk = { path = "../.." }
cloudevents-sdk-tide = { path = "../../cloudevents-sdk-tide" }
tide = { version = "0.16" }
async-std = { version = "1", features = ["attributes"] }
tide-websockets = "0.3.0"
futures-util = "0.3.8"
serde_json = "1.0.64"
chrono = { version = "^0.4", features = ["serde"] }

[workspace]
[workspace]
62 changes: 62 additions & 0 deletions example-projects/tide-example/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<!DOCTYPE html>
<html lang="en">

<head>
<title>CloudEvent UI</title>
<meta charset="utf-8">
<meta name="author" content="Anton Whalley">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<style>
textarea {
width: 500px;
height: 300px;
}

</style>
</head>
<body>
CloudEvent UI
<br />
<textarea id="msg">
{
"specversion" : "1.0",
"type" : "com.example.someevent",
"source" : "/mycontext",
"id" : "A234-1234-1234",
"time" : "2018-04-05T17:31:00Z",
"comexampleextension1" : "value",
"comexampleothervalue" : 5,
"datacontenttype" : "text/xml",
"data" : "<much wow=\"xml\"/>"
}
</textarea>
<br/>
<button onclick="send()">Send</button>
<div>Responses:</div>
<div id="responses"></div>
<script>
let io;
document.addEventListener("DOMContentLoaded", function() {
// connect to ws
const ws_url = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}${window.location.pathname}`;
io = new WebSocket( ws_url, ["cloudevents.json", "cloudevents.avro"] );
io.onmessage = function (event) {
let msg = document.getElementById("responses").innerHTML;
msg += JSON.stringify(event.data);
console.log(event.data);
document.getElementById("responses").innerHTML = msg;
}
} );

function send() {
let msg = document.getElementById("msg").value;
console.log(msg);
io.send(msg);
}



</script>
</body>
</html>
87 changes: 61 additions & 26 deletions example-projects/tide-example/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,73 @@
use cloudevents::{EventBuilder, EventBuilderV10, Event};
use chrono::Utc;
use cloudevents::{Event, EventBuilder, EventBuilderV10};
use cloudevents_sdk_tide::*;
use tide::{Response, Request, Body};

pub async fn get(_req: Request<()>) -> tide::Result {
Ok(Response::new(200).event(
EventBuilderV10::new()
.id("0001")
.ty("example.test")
.source("http://localhost/")
.data("text/xml", "<xml data=\"hello\" />".as_bytes().to_vec())
.build()
.expect("No error while building the event"),
).await?
)
}
use futures_util::StreamExt;
use serde_json::json;
use tide::log;
use tide::{Body, Request, Response};
use tide_websockets::{Message, WebSocket, WebSocketConnection};

pub async fn post(req: Request<()>) -> tide::Result {
let evtresp: Event = req.to_event().await?;
let response = Response::builder(200)
.body(Body::from_json(&evtresp)?)
.build();
Ok(response)
}
pub async fn get(_req: Request<()>) -> tide::Result {
Ok(Response::new(200)
.event(
EventBuilderV10::new()
.id("0001")
.ty("example.test")
.source("http://localhost/")
.data("text/xml", "<xml data=\"hello\" />".as_bytes().to_vec())
.build()
.expect("No error while building the event"),
)
.await?)
}

//Test post with
// curl -H "Content-Type:text/plain" -H "ce-specversion:1.0" -H "ce-id:0001" -H "ce-source:http://localhost" -H "ce-type:example.test" -d "hello" http://127.0.0.1:8080/
#[async_std::main]
pub async fn post(req: Request<()>) -> tide::Result {
let evtresp: Event = req.to_event().await?;
let response = Response::builder(200)
.body(Body::from_json(&evtresp)?)
.build();
Ok(response)
}

//Test post with
// curl -H "Content-Type:text/plain" -H "ce-specversion:1.0" -H "ce-id:0001" -H "ce-source:http://localhost" -H "ce-type:example.test" -d "hello" http://127.0.0.1:8080/
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();

let mut app = tide::new();
let mut index = app.at("/");
index.get(get);
index.post(post);

app.at("/socket")
.with(
WebSocket::new(
|_req: Request<_>, mut wsc: WebSocketConnection| async move {
while let Some(Ok(Message::Text(message))) = wsc.next().await {
let time = Utc::now();
let msg = json!({ "hello":"world" });
let v: Event = serde_json::from_str(&message).unwrap();
println!("{:?}", v);
let resp = EventBuilderV10::new()
.id("0001")
.ty("example.test")
.source("http://localhost/")
.time(time)
.data("application/cloudevents+json", msg)
.build()
.unwrap();
wsc.send_json(&resp).await?;
}

Ok(())
},
)
.with_protocols(&["cloudevents.json"]),
)
.get(|_| async { Ok(Body::from_file("./public/index.html").await?) });

log::info!("Socket UI: http://127.0.0.1:8080/socket");
app.listen("127.0.0.1:8080").await?;
Ok(())
}
}

0 comments on commit 205e16a

Please sign in to comment.