zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use actix_web::{rt, web, Error, HttpRequest, HttpResponse, Responder};
use tokio::sync::broadcast;

use crate::core::{request2::Render, R};

/// Handshake and start basic WebSocket handler.
///
/// This example is just for demonstration of simplicity. In reality, you likely want to include
/// some handling of heartbeats for connection health tracking to free up server resources when
/// connections die or network issues arise.
pub async fn basic_ws(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;

    // spawn websocket handler (and don't await it) so that the response is returned immediately
    rt::spawn(super::echo_basic_ws(session, msg_stream));

    Ok(res)
}

/// Handshake and start WebSocket handler with heartbeats.
pub async fn heartbeat_ws(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;

    // spawn websocket handler (and don't await it) so that the response is returned immediately
    rt::spawn(super::echo_heartbeat_ws(session, msg_stream));

    Ok(res)
}

/// Handshake and start broadcast WebSocket handler with heartbeats.
pub async fn broadcast_ws(
    req: HttpRequest,
    stream: web::Payload,
    tx: web::Data<broadcast::Sender<web::Bytes>>,
) -> Result<HttpResponse, Error> {
    let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;

    // spawn websocket handler (and don't await it) so that the response is returned immediately
    rt::spawn(super::echo_broadcast_ws(
        session,
        msg_stream,
        tx.subscribe(),
    ));

    Ok(res)
}

/// Send message to clients connected to broadcast WebSocket.
pub async fn send_to_broadcast_ws(
    request: HttpRequest,
    body: web::Bytes,
    tx: web::Data<broadcast::Sender<web::Bytes>>,
) -> Result<impl Responder, Error> {
    tx.send(body).map_err(|e| {
        log::error!("send_to_broadcast_ws: error={:?}", e);
        actix_web::error::ErrorInternalServerError(e)
    })?;

    // Ok(HttpResponse::NoContent())
    Ok(request.json(200, R::ok(true)))
}