use tokio::{io::AsyncWriteExt, net::TcpStream};
use crate::protocol::http::{Request, Response};
pub static mut PROXY_TARGET: Vec<String> = vec![];
#[derive(Debug, Clone)]
pub enum BalancingMode {
WEIGHT,
RANDOM,
POLLING,
}
#[derive(Debug, Clone)]
pub struct Proxy {
request: Request,
response: Response,
}
impl Proxy {
pub async fn load_balancing(
host: &str,
port: &str,
request: Request,
mode: BalancingMode,
) -> Result<Self, String> {
match mode {
BalancingMode::WEIGHT => Proxy::to(host, port, request).await,
BalancingMode::RANDOM => Proxy::to(host, port, request).await,
BalancingMode::POLLING => Proxy::to(host, port, request).await,
_ => Err("".to_string()),
}
}
pub async fn to(host: &str, port: &str, request: Request) -> Result<Self, String> {
let t = TcpStream::connect(format!("{}:{}", host, port))
.await
.unwrap();
let (r, mut w) = t.into_split();
let _ = w.write_all(&request.raw()).await;
match Response::multi_thread_decode(r).await {
Ok(response) => {
return Ok(Proxy {
request: request,
response: response,
});
}
Err(_) => {
return Err("".to_string());
}
}
}
}