use std::{pin::Pin, sync::Arc}; use hyper::{ Request, body::Incoming, service::Service, }; use tokio::sync::Mutex; use crate::{ db::{BoxyDatabase, Endpoint}, server::{GeneralResponse, TcpIntercept}, }; use super::proxy::ProxyService; #[derive(Debug, Clone)] pub struct ControllerService { pub database: Arc>, } impl TcpIntercept for ControllerService { fn stream(&mut self, _: &tokio::net::TcpStream) {} } impl Service> for ControllerService { type Response = GeneralResponse; type Error = hyper::Error; type Future = Pin> + Send>>; fn call(&self, req: Request) -> Self::Future { let database = self.database.clone(); Box::pin(async move { let hostname = req .headers() .get(hyper::header::HOST) .unwrap() .to_str() .unwrap() .to_string(); let endpoints = Endpoint::get_by_hostname(*database.lock().await, hostname.clone()) .await .unwrap(); let endpoint = endpoints.first().unwrap(); let proxy = ProxyService { address: format!("{}:{}", endpoint.address.clone(), endpoint.port), hostname, }; proxy.call(req).await }) } }