use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub enum Message {
Text(String),
Binary(Vec<u8>),
Ping(Vec<u8>),
Pong(Vec<u8>),
Close(Option<CloseFrame>),
}
impl Message {
pub fn from_axum(msg: axum::extract::ws::Message) -> Self {
match msg {
axum::extract::ws::Message::Text(text) => Message::Text(text.to_string()),
axum::extract::ws::Message::Binary(data) => Message::Binary(data.to_vec()),
axum::extract::ws::Message::Ping(data) => Message::Ping(data.to_vec()),
axum::extract::ws::Message::Pong(data) => Message::Pong(data.to_vec()),
axum::extract::ws::Message::Close(close_frame) => {
Message::Close(close_frame.map(|f| CloseFrame {
code: f.code,
reason: f.reason.to_string(),
}))
}
}
}
pub fn into_axum(self) -> axum::extract::ws::Message {
match self {
Message::Text(text) => {
axum::extract::ws::Message::Text(axum::extract::ws::Utf8Bytes::from(text.as_str()))
}
Message::Binary(data) => {
axum::extract::ws::Message::Binary(axum::body::Bytes::from(data))
}
Message::Ping(data) => axum::extract::ws::Message::Ping(axum::body::Bytes::from(data)),
Message::Pong(data) => axum::extract::ws::Message::Pong(axum::body::Bytes::from(data)),
Message::Close(close_frame) => {
axum::extract::ws::Message::Close(close_frame.map(|f| {
use axum::extract::ws::CloseCode;
let code = CloseCode::from(f.code);
axum::extract::ws::CloseFrame {
code,
reason: axum::extract::ws::Utf8Bytes::from(f.reason.as_str()),
}
}))
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloseFrame {
pub code: u16,
pub reason: String,
}