Created
January 19, 2015 04:53
-
-
Save TheNeikos/c272767d8aa7679b7ac3 to your computer and use it in GitHub Desktop.
Simple HTTP Server
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
extern crate getopts; | |
use std::io::{TcpListener, TcpStream}; | |
use std::io::{Acceptor, Listener}; | |
use std::io::IoErrorKind; | |
use std::thread::Thread; | |
use std::os; | |
use getopts::{optopt, optflag, getopts, OptGroup, usage}; | |
fn print_usage(program: &str, opts: &[OptGroup]) { | |
let brief = format!("Usage: {} [options]", program); | |
println!("{}", usage(brief.as_slice(), opts)); | |
} | |
fn handle_client(mut stream: TcpStream) { | |
let bytes = match stream.read_to_end() { | |
Ok(bytes) => { bytes } | |
Err(e) => { println!("We got an error: {}", e); return; } | |
}; | |
let text = String::from_utf8(bytes).unwrap(); | |
let _ = stream.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\ncontent-length: 21\r\n\r\n<h1>Test content</h1>"); | |
println!("{}", text); | |
} | |
fn main() { | |
let args = os::args(); | |
let program = args[0].clone(); | |
let opts = &[ | |
optopt("p", "port", "set the port to bind to", "PORT"), | |
optopt("a", "address", "address to bind to", "ADDR"), | |
optflag("h", "help", "print this menu") | |
]; | |
let matches = match getopts(args.tail(), opts) { | |
Ok(m) => { m } | |
Err(f) => { panic!("{}", f) } | |
}; | |
if matches.opt_present("h") { | |
print_usage(program.as_slice(), opts); | |
return; | |
} | |
let port = match matches.opt_str("p") { | |
Some(port) => { port } | |
None => { | |
print_usage(program.as_slice(), opts); | |
return; | |
} | |
}; | |
let address = match matches.opt_str("a") { | |
Some(addr) => { addr } | |
None => { "0.0.0.0".to_string() } | |
}; | |
let full_address = address + ":" + port.as_slice(); | |
let listener = TcpListener::bind(full_address.as_slice()).unwrap(); | |
let mut acceptor = listener.listen().unwrap(); | |
for stream in acceptor.incoming() { | |
match stream { | |
Err(e) => { println!("Error in stream: {}", e) } | |
Ok(stream) => { | |
Thread::spawn(move|| { | |
handle_client(stream); | |
}); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment