Skip to content

Instantly share code, notes, and snippets.

@quux00
Last active August 29, 2015 13:56
Show Gist options
  • Save quux00/9181501 to your computer and use it in GitHub Desktop.
Save quux00/9181501 to your computer and use it in GitHub Desktop.
Snippet of web server code in Rust
use std::io::EndOfFile;
use std::io::io_error;
// ...
fn respond_with_static_file(stream: Option<std::io::net::tcp::TcpStream>, path: &Path) {
let mut stream = stream;
let sz = 16384;
let result = io::result(|| File::open(path));
match result {
Ok(fopt) => {
let mut file = fopt.unwrap();
let mut keep_reading = true;
io_error::cond.trap(|e| {
keep_reading = false;
if e.kind != EndOfFile {
println!("WARN: Error while reading file: {:s} - {:?}", path.display().to_str(), e);
}
}).inside(|| {
stream.write(HTTP_OK.as_bytes());
while keep_reading {
let buf = file.read_bytes(sz);
stream.write(buf); // errors from here will also be caught by above trap hdlr
}
});
}
Err(ioerror) => println!("WARN: {:?}", ioerror)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment