Skip to content

Instantly share code, notes, and snippets.

@campaul
Created July 1, 2014 00:08
Show Gist options
  • Save campaul/c56c718ff8074a8af4d4 to your computer and use it in GitHub Desktop.
Save campaul/c56c718ff8074a8af4d4 to your computer and use it in GitHub Desktop.
First attempt at responding to HTTP
use std::io::{Acceptor, Listener};
use std::io::net::tcp::TcpListener;
use std::io::net::ip::SocketAddr;
use std::from_str::from_str;
use std::io::File;
use std::io::IoError;
use std::io::{BufferedReader, BufferedWriter};
fn read_file(path: Path) -> Result<~str, IoError> {
let mut file = match File::open(&path) {
Err(why) => return Err(why),
Ok(file) => file,
};
let data = match file.read_to_str() {
Err(why) => fail!("couldn't read {}: {}", path.display(), why.desc),
Ok(string) => string,
};
return Ok(data);
}
fn main() {
let resp_bytes = bytes!("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n");
let not_found = bytes!("HTTP/1.0 404 Not Found\r\nContent-Type: text/html\r\n\r\nFile Not Found");
let address: SocketAddr = from_str("127.0.0.1:8080").expect("malformed address");
let listener = TcpListener::bind(address);
let mut acceptor = listener.listen();
for stream in acceptor.incoming() {
let mut reader = BufferedReader::new(stream.clone());
let mut writer = BufferedWriter::new(stream.clone());
let input = reader.read_line().ok().unwrap_or(~"nothing");
let tokens: ~[&str] = input.split(' ').collect();
let file = tokens[1];
let path = Path::new(file.trim_left_chars(&'/'));
match read_file(path) {
Ok(string) => writer.write(resp_bytes + string.as_bytes()),
Err(why) => writer.write(not_found),
};
writer.flush().ok();
}
drop(acceptor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment