Skip to content

Instantly share code, notes, and snippets.

@abhi-bit
Last active August 29, 2015 14:20
Show Gist options
  • Save abhi-bit/b304f01e3b98323a49ba to your computer and use it in GitHub Desktop.
Save abhi-bit/b304f01e3b98323a49ba to your computer and use it in GitHub Desktop.
Vanilla web server
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::str;
use std::thread;
fn handle_client(mut stream: TcpStream) {
match stream.peer_addr() {
Err(_) => (),
Ok(pn) => println!("Received connection from: [{}]", pn),
}
let mut buf = [0;100];
let _ = stream.read(&mut buf);
match str::from_utf8(&buf) {
Err(e) => println!("Received request error:\n{}", e),
Ok(body) => println!("Received request body:\n{}", body),
}
let response = "HTTP/1.1 200OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
Hello World\r\n";
let _ = stream.write(response.as_bytes());
println!("Connection terminates");
}
fn main() {
let addr = "127.0.0.1:8000";
let listener = TcpListener::bind(addr).unwrap();
println!("Listening on [{}]", addr);
for stream in listener.incoming() {
match stream {
Err(_) => (),
Ok(mut stream) => {
thread::spawn(move || {
handle_client(stream)
});
},
}
}
drop(listener);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment