zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use actix::Message as ActixMessage;
use bytestring::ByteString;
use serde_json::{json, Value};

#[derive(
    serde::Serialize,
    serde::Deserialize,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Debug,
    Hash,
    strum_macros::EnumString,
)]
#[strum(ascii_case_insensitive)]
pub enum OutputMessageType {
    Msg,
    Err,
    Info,
    ServerTime,
    Startup, // 最后一次启动时间
}

#[derive(serde::Serialize)]
pub enum TypedMessage {
    TextMessage(String),
    JsonMessage(Value),
}

#[derive(serde::Serialize, ActixMessage)]
#[rtype(result = "()")]
pub struct OutputMessage {
    pub ty: OutputMessageType,
    pub id: String,
    pub msg: TypedMessage,
}

impl OutputMessage {
    pub fn err(msg: String, id: &str) -> Self {
        OutputMessage {
            ty: OutputMessageType::Err,
            msg: TypedMessage::TextMessage(msg),
            id: id.to_string(),
        }
    }

    pub fn info(msg: String, id: &str) -> Self {
        OutputMessage {
            ty: OutputMessageType::Info,
            msg: TypedMessage::TextMessage(msg),
            id: id.to_string(),
        }
    }

    pub fn output(&self) -> String {
        let mut vl = json! ({"ty": self.ty, "id": self.id});

        match &self.msg {
            TypedMessage::TextMessage(msg) => vl["msg"] = json!(msg),
            TypedMessage::JsonMessage(val) => vl["msg"] = val.clone(),
        }

        serde_json::to_string(&vl).unwrap()
    }
}

impl From<OutputMessage> for ByteString {
    fn from(val: OutputMessage) -> Self {
        let json_string = serde_json::to_string(&val).unwrap();
        let byte_string: ByteString = ByteString::from(json_string);

        byte_string
    }
}