Skip to content

Instantly share code, notes, and snippets.

@jwreagor
Forked from ayende/proxy.rs
Created January 13, 2017 15:56
Show Gist options
  • Save jwreagor/c91d24a9518790317237398b69e7505f to your computer and use it in GitHub Desktop.
Save jwreagor/c91d24a9518790317237398b69e7505f to your computer and use it in GitHub Desktop.
#![feature(lookup_host)]
extern crate futures;
extern crate tokio_core;
extern crate rand;
use rand::Rng;
use std::env;
use futures::{Future, Stream};
use tokio_core::io::{copy, Io};
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
use tokio_core::net::TcpStream;
fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let addr = "127.0.0.1:0".parse().unwrap();
let sock = TcpListener::bind(&addr, &handle).unwrap();
println!("Listening on 127.0.0.1:{}",
sock.local_addr().unwrap().port());
let mut urls: Vec<std::net::SocketAddr> = Vec::new();
for url in env::args().skip(1) {
let parts: Vec<&str> = url.split(":").collect();
print!("{} was resolved to: ", parts[0]);
for mut host in std::net::lookup_host(parts[0]).unwrap() {
host.set_port(parts[1].parse().unwrap());
print!(" {},", host);
urls.push(host);
}
println!();
}
let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
let index = rand::thread_rng().gen_range(0, urls.len());
let (client_read, client_write) = client_stream.split();
println!("{} connected and will be forwarded to {}", &remote_addr, &urls[index]);
let send_data = TcpStream::connect(&urls[index], &handle).and_then(|server_stream| {
let (server_read, server_write) = server_stream.split();
let client_to_server = copy(client_read, server_write);
let server_to_client = copy(server_read, client_write);
client_to_server.join(server_to_client)
})
// erase the types
.map(|(_client_to_server,_server_to_client)| {} ).map_err(|_err| {} );
handle.spawn(send_data);
Ok(())
});
core.run(server).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment