Last active
May 12, 2021 14:47
-
-
Save sdressler/f9186dca5a30bb2b0fc5c5bbabfee2e2 to your computer and use it in GitHub Desktop.
Simple Rust Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::net::TcpListener; | |
use std::net::TcpStream; | |
use std::thread::spawn; | |
use std::io::prelude::*; | |
// mod cache; | |
// pub mod state; | |
// use state::State; | |
fn main() { | |
let server = TcpListener::bind("127.0.0.1:15432").unwrap(); | |
for client in server.incoming() { | |
println!("New conn..."); | |
let client = client.unwrap(); | |
spawn(move || { | |
handle_connection(client); | |
}); | |
} | |
} | |
fn handle_connection(mut client: TcpStream) { | |
let mut upstream = TcpStream::connect("127.0.0.1:5432").unwrap(); | |
upstream.set_nodelay(true).unwrap(); | |
let mut client_clone = client.try_clone().unwrap(); | |
let mut upstream_clone = upstream.try_clone().unwrap(); | |
let t1 = spawn(move || { | |
pipe(&mut client, &mut upstream, true); | |
}); | |
let t2 = spawn(move || { | |
pipe(&mut upstream_clone, &mut client_clone, false) | |
}); | |
t1.join().unwrap(); | |
t2.join().unwrap(); | |
} | |
fn pipe(input: &mut TcpStream, output: &mut TcpStream, is_forth: bool) { | |
let mut buffer = [0u8; 32_768]; | |
let mut reader = BufReader::new(input); | |
let mut writer = BufWriter::new(output); | |
loop { | |
match reader.read(&mut buffer) { | |
Ok(size) => { | |
if size == 0 { | |
writer.into_inner().unwrap().shutdown(std::net::Shutdown::Both).unwrap(); | |
break; | |
} | |
/* | |
let mut size = size; | |
if is_forth { | |
size = cache::processor_forth(size, &mut buffer); | |
} | |
*/ | |
if writer.write(&buffer[..size]).is_ok() { | |
writer.flush().unwrap(); | |
} | |
}, | |
Err(error) => { println!("Error: {:?}", error); } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment