Skip to content

Instantly share code, notes, and snippets.

@theoparis
Created February 20, 2022 08:41
Show Gist options
  • Save theoparis/b89227cb2204751e54c095265e8594ec to your computer and use it in GitHub Desktop.
Save theoparis/b89227cb2204751e54c095265e8594ec to your computer and use it in GitHub Desktop.
Proxy server issue #1
use std::{env, net::IpAddr, str::FromStr};
use fdpl::{server::ProxyServer, types::Route};
use tide::Request;
#[tokio::main]
async fn main() {
env_logger::init_from_env(
env_logger::Env::default().default_filter_or("info"),
);
// start the server with the port from the environment variable
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = IpAddr::from_str("0.0.0.0").unwrap();
let port = u16::from_str(&port).unwrap();
// This is the variable im trying to access from within the api requests
let mut server = ProxyServer::new(addr, port);
server.start().await;
// start a api to add/remove domains
let mut app = tide::new();
app.at("/domains").post(|mut req: Request<()>| async move {
let domain = req.param("domain").unwrap();
let route = req.body_json::<Route>().await.unwrap();
let res = server.add_domain(domain.to_string(), route).await;
match res {
Ok(_) => Ok(tide::Response::new(200)),
Err(e) => {
let mut res = tide::Response::new(500);
res.set_body(e.to_string());
Ok(res)
}
}
});
app.at("/domains")
.delete(|mut req: Request<()>| async move {
let domain = req.param("domain").unwrap();
let res = server.remove_domain(domain.to_string()).await;
match res {
Ok(_) => {
let mut res = tide::Response::new(200);
res.set_body("Domain removed".to_string());
Ok(res)
}
Err(e) => {
let mut res = tide::Response::new(500);
res.set_body(e.to_string());
Ok(res)
}
}
});
app.at("/domains").get(|mut req| async move {
let res = server.get_data();
Ok(serde_json::to_string(&res).unwrap())
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment