Skip to content

Instantly share code, notes, and snippets.

@daschl
Forked from normanmaurer/main.rs
Created December 21, 2015 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daschl/e6240432be623352fa2d to your computer and use it in GitHub Desktop.
Save daschl/e6240432be623352fa2d to your computer and use it in GitHub Desktop.
extern crate hyper;
use hyper::server::{Server, Request, Response};
use hyper::status::StatusCode;
use hyper::header::{Host, UserAgent};
use hyper::uri::RequestUri;
use hyper::client::Client;
use std::io;
use std::fs::File;
const CACHE_DIR: &'static str = "/Users/michael/cache";
fn send_request(path: &str) -> hyper::client::Response {
let client = Client::new();
let client_req = client.get(&*format!("{}{}", "http://repo1.maven.org/", path));
return client_req.header(Host {
hostname: String::from("repo1.maven.org"),
port: Some(80),
}).header(UserAgent(String::from("mcache"))).send().unwrap();
}
fn proxy_response(path: &str, resp: Response) {
let mut client_resp = send_request(&path);
io::copy(&mut client_resp, &mut resp.start().unwrap()).unwrap();
}
fn handle_jar(path: &str, mut resp: Response) {
let jar = CACHE_DIR.to_string() + &path;
match File::open(&jar) {
Ok(mut file) => {
if let Ok(mut r) = resp.start() {
if let Err(e) = io::copy(&mut file, &mut r) {
println!("Error during copy file {} to reponse {:?}", jar, e);
}
}
// Nothing we can do if this happens, as the response is broken
// somehow.
},
Err(_) => {
let mut client_resp = send_request(&path);
match jar.rfind('/') {
Some(index) => {
let _ = std::fs::create_dir_all(&jar[0..index]);
match File::create(&jar) {
Ok(mut file) => {
match io::copy(&mut client_resp, &mut file) {
Ok(_) => {
match File::open(&jar) {
Ok(mut file) => {
if let Ok(mut r) = resp.start() {
if let Err(e) = io::copy(&mut file, &mut r) {
println!("Error during copy file {} to reponse {:?}", jar, e);
}
}
// Nothing we can do if this happens, as the response is broken
// somehow.
},
Err(_) => {
// TODO: Fix me
}
}
},
Err(_) => {
*resp.status_mut() = StatusCode::InternalServerError;
}
}
},
Err(_) => {
// Can't create the file let us just proxy the response
if let Ok(mut r) = resp.start() {
if let Err(e) = io::copy(&mut client_resp, &mut r) {
println!("Error during copy client response to server reponse {:?}", e);
}
}
}
}
},
None => {
proxy_response(&path, resp);
}
}
}
}
}
fn handle(req: Request, mut resp: Response) {
match req.method {
hyper::Get => match req.uri {
RequestUri::AbsolutePath(ref p) if p.ends_with(".jar") => handle_jar(&p, resp),
RequestUri::AbsolutePath(p) => proxy_response(&p, resp),
_ => *resp.status_mut() = StatusCode::InternalServerError
},
_ => *resp.status_mut() = StatusCode::MethodNotAllowed
}
}
fn main() {
let server = Server::http("0.0.0.0:9990").unwrap();
server.handle(handle).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment