65 lines
1.9 KiB
Rust
Raw Normal View History

2026-01-24 22:59:20 +00:00
use crate::api::rpc::RpcHandler;
use crate::config::Config;
use anyhow::Result;
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use std::sync::Arc;
use tracing::debug;
pub struct ApiHandler {
config: Config,
rpc_handler: Arc<RpcHandler>,
// Add other handlers here (websocket, static files, etc.)
}
impl ApiHandler {
pub async fn new(config: Config) -> Result<Self> {
let rpc_handler = Arc::new(RpcHandler::new(config.clone()).await?);
Ok(Self {
config,
rpc_handler,
})
}
pub async fn handle_request(
&self,
req: Request<http_body_util::Body<Bytes>>,
) -> Result<Response<Full<Bytes>>> {
let path = req.uri().path();
let method = req.method();
// Convert Incoming body to bytes
let (parts, body) = req.into_parts();
let collected = body.collect().await
.map_err(|e| anyhow::anyhow!("Failed to read body: {}", e))?;
let body_bytes = collected.to_bytes();
// Reconstruct request with Full<Bytes> body for RPC handler
let req_with_bytes = Request::from_parts(parts, Full::new(body_bytes));
debug!("{} {}", method, path);
// Route requests
match (method, path) {
(&Method::POST, "/rpc/v1") => {
self.rpc_handler.handle(req_with_bytes).await
}
(&Method::GET, "/health") => {
Ok(Response::builder()
.status(StatusCode::OK)
.body(Full::new(Bytes::from("OK")))
.unwrap())
}
_ => {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(Bytes::from("Not Found")))
.unwrap())
}
}
}
}