use std::fmt::{Display, format, Formatter}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use actix_web::{web, App, HttpResponse, HttpServer, get, Responder, HttpRequest}; use actix_web::web::Redirect; #[derive(Clone)] enum Protocol { HTTP, HTTPS } impl Display for Protocol { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Protocol::HTTP => write!(f, "http://"), Protocol::HTTPS => write!(f, "https://") } } } #[derive(Clone)] struct DomainLinkConfig { domain: String, protocol: Protocol, target: String, } #[derive(Clone)] struct Config { redirects: Vec, ports: Vec, addresses: Vec, } #[actix_web::main] async fn main() -> std::io::Result<()> { let config = Config { redirects: vec![ DomainLinkConfig { domain: "neshura.me".to_owned(), protocol: Protocol::HTTPS, target: "neshweb.net".to_owned(), }, DomainLinkConfig { domain: "lemmy.neshura.me".to_owned(), protocol: Protocol::HTTPS, target: "bookwormstory.social/u/neshura".to_owned() }, DomainLinkConfig { domain: "test2.neshura.me".to_owned(), protocol: Protocol::HTTPS, target: "neshweb.net".to_owned() } ], ports: vec![8080, 8090], addresses: vec![ IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), IpAddr::V4(Ipv4Addr::new(192, 168, 178, 11)) ], }; let mut server = HttpServer::new(move || { App::new() .app_data(web::Data::new(config.redirects.clone())) .service(handle) .service(dry_handle) }); for address in &config.addresses { for port in &config.ports { server = server.bind((address.clone(), port.clone()))? } } server.run().await } #[get("/")] async fn handle(redirects: web::Data>, request: HttpRequest) -> impl Responder { if let Some(host_raw) = request.headers().get("host") { let host = host_raw.to_str().expect("host conversion to string should never fail"); println!("{host}"); for redirect in redirects.iter() { if redirect.domain == host { return HttpResponse::PermanentRedirect().insert_header(("location", format!("{}{}", redirect.protocol, redirect.target).as_str())).finish(); } } let fail_msg = format!("No Redirect for {host} found"); return HttpResponse::NotFound().body(fail_msg) } HttpResponse::NotFound().body("Host not specified") } #[get("/dry")] async fn dry_handle(redirects: web::Data>, request: HttpRequest) -> impl Responder { if let Some(host_raw) = request.headers().get("host") { let host = host_raw.to_str().expect("host conversion to string should never fail"); println!("{host}"); for redirect in redirects.iter() { if redirect.domain == host { let body = format!("Redirecting: {} -> {}{}", host, redirect.protocol, redirect.target); return HttpResponse::Ok().body(body); } } let fail_msg = format!("No Redirect for {host} found"); return HttpResponse::NotFound().body(fail_msg) } HttpResponse::NotFound().body("Host not specified") }