simple_proxy/
lib.rs

1#[macro_use]
2extern crate log;
3#[cfg(feature = "router")]
4#[macro_use]
5extern crate serde_derive;
6
7pub mod middlewares;
8pub mod proxy;
9
10use hyper::server::conn::AddrStream;
11use hyper::service::make_service_fn;
12use hyper::Server;
13use std::fmt;
14use std::{
15    convert::Infallible,
16    sync::{Arc, Mutex},
17};
18
19use crate::proxy::middleware::Middleware;
20use crate::proxy::service::ProxyService;
21
22type Middlewares = Arc<Mutex<Vec<Box<dyn Middleware + Send + Sync>>>>;
23
24#[derive(Debug, Clone, Copy)]
25pub enum Environment {
26    Production,
27    Staging,
28    Development,
29}
30
31impl fmt::Display for Environment {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        match self {
34            Environment::Production => write!(f, "production"),
35            Environment::Staging => write!(f, "staging"),
36            Environment::Development => write!(f, "development"),
37        }
38    }
39}
40
41impl std::str::FromStr for Environment {
42    type Err = String;
43
44    fn from_str(s: &str) -> Result<Self, Self::Err> {
45        match s {
46            "production" => Ok(Environment::Production),
47            "staging" => Ok(Environment::Staging),
48            "development" => Ok(Environment::Development),
49            _ => Err(String::from(
50                "valid values: production, staging, development",
51            )),
52        }
53    }
54}
55
56pub struct SimpleProxy {
57    port: u16,
58    environment: Environment,
59    middlewares: Middlewares,
60}
61
62impl SimpleProxy {
63    pub fn new(port: u16, environment: Environment) -> Self {
64        SimpleProxy {
65            port,
66            environment,
67            middlewares: Arc::new(Mutex::new(vec![])),
68        }
69    }
70
71    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
72        let addr = ([0, 0, 0, 0], self.port).into();
73
74        info!("Running proxy in {} mode on: {}", self.environment, &addr);
75
76        let middlewares = Arc::clone(&self.middlewares);
77        let make_svc = make_service_fn(move |socket: &AddrStream| {
78            let remote_addr = socket.remote_addr();
79            let middlewares = middlewares.clone();
80            debug!("Handling connection for IP: {}", &remote_addr);
81
82            async move { Ok::<_, Infallible>(ProxyService::new(middlewares, remote_addr)) }
83        });
84
85        let server = Server::bind(&addr).serve(make_svc);
86
87        if let Err(e) = server.await {
88            eprintln!("server error: {}", e);
89        }
90        Ok(())
91    }
92
93    pub fn add_middleware(&mut self, middleware: Box<dyn Middleware + Send + Sync>) {
94        self.middlewares.lock().unwrap().push(middleware)
95    }
96}