Skip to content

Instantly share code, notes, and snippets.

@zsyed91
Created February 17, 2015 03:31
Show Gist options
  • Save zsyed91/8665f5b32073efa2b375 to your computer and use it in GitHub Desktop.
Save zsyed91/8665f5b32073efa2b375 to your computer and use it in GitHub Desktop.
Rust webserver
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
fn main() {
let listener = TcpListener::bind("127.0.0.1:80").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
handle_client(stream);
}
Err(e) => {
println!("Connection failure!");
}
}
}
drop(listener);
}
fn handle_client(mut stream: TcpStream) {
println!("Client connected, sending response");
let html = "<html><head><title>Rust</title></head><body><p>Rust Server!</p></body></html>".to_string();
let output = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
html.len(),
html);
stream.write(output.as_bytes());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment