56 lines
1.4 KiB
Rust
56 lines
1.4 KiB
Rust
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<Mutex<&'static mut BoxyDatabase>>,
|
|
}
|
|
|
|
impl TcpIntercept for ControllerService {
|
|
fn stream(&mut self, _: &tokio::net::TcpStream) {}
|
|
}
|
|
|
|
impl Service<Request<Incoming>> for ControllerService {
|
|
type Response = GeneralResponse;
|
|
type Error = hyper::Error;
|
|
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
|
|
|
fn call(&self, req: Request<Incoming>) -> 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
|
|
})
|
|
}
|
|
}
|