Skip to content

Commit

Permalink
Change POST endpoint to accept just text/plain.
Browse files Browse the repository at this point in the history
* We deal with text only, for now.
* The JSON had just one field, which is needless complexity.
* When we want the websocket to post JSON, we would need to escape all
  JSON. We no longer need this.
  • Loading branch information
berkes committed Sep 19, 2022
1 parent 01a917b commit 5f4016b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 34 deletions.
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,8 @@ a websocket.
# > my name is Foo and I am a Bar
# > { "message": "this would be JSON" }
```
Leave this running for now.

3. Fire websocket messages to the client using a normal HTTP library. e.g. `curl`.
```
curl -X POST -H"Content-type: application/json" \
--data '{"content": "Hello from the server"}' \
http://127.0.0.1:3000/messages
```
We should see wscat print the message to the console.

4. Check messages received from client:
3. Check messages received from client:
```bash
curl http://127.0.0.1:3000/messages | jq
# [
Expand All @@ -48,6 +39,15 @@ a websocket.
# ]
```

4. Fire websocket messages to the client using a normal HTTP library. e.g. `curl`.
```
wscat --connect http://127.0.0.1:3000/ws
curl -X POST -H"Content-type: text/plain; charset=UTF-8" \
--data 'Hello from the server 👋' \
http://127.0.0.1:3000/messages
```
We should see wscat print the message to the console.

### Install

In order to install the platform on development machine, run
Expand Down
25 changes: 4 additions & 21 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,14 @@ use futures::{
stream::{SplitSink, SplitStream, StreamExt},
};
use log::{debug, error, info};
use serde::{Deserialize, Serialize};
use std::{
fmt::Display,
sync::{Arc, RwLock},
};
use serde::Serialize;
use std::sync::{Arc, RwLock};
use tokio::sync::broadcast;

use crate::config::Config;

mod config;

#[derive(Deserialize)]
struct MockMessage {
content: String,
}

type SharedState = Arc<AppState>;

struct AppState {
Expand All @@ -38,12 +30,6 @@ struct MessageList {
messages: Vec<String>,
}

impl Display for MockMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.content)
}
}

#[tokio::main]
async fn main() {
env_logger::init();
Expand Down Expand Up @@ -81,11 +67,8 @@ async fn list_messages(Extension(app_state): Extension<SharedState>) -> impl Int
(StatusCode::OK, Json(messages))
}

async fn create_message(
Json(payload): Json<MockMessage>,
app_state: Extension<SharedState>,
) -> impl IntoResponse {
match app_state.tx.send(payload.content.clone()) {
async fn create_message(payload: String, app_state: Extension<SharedState>) -> impl IntoResponse {
match app_state.tx.send(payload.clone()) {
Ok(_) => debug!("generating mock websocket message: {}", payload),
Err(_) => error!("failed generating websocket message"),
}
Expand Down
12 changes: 9 additions & 3 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,21 @@ fn test_can_send_messages_to_client() {
let client = reqwest::blocking::Client::new();
let resp = client
.post(format_url(port, "messages"))
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.body("{\"content\": \"hello from server\"}")
.header(
CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=UTF-8"),
)
.body("hello from server 👋")
.send()
.unwrap();

assert!(resp.status().is_success());

let message = connection.recv_message().unwrap();
assert_eq!(OwnedMessage::Text("hello from server".to_string()), message);
assert_eq!(
OwnedMessage::Text("hello from server 👋".to_string()),
message
);

drop(test_control);
}
Expand Down

0 comments on commit 5f4016b

Please sign in to comment.