Skip to content

Instantly share code, notes, and snippets.

@tenthree
Created September 5, 2018 17:21
Show Gist options
  • Save tenthree/7dbda9ef8642bfe88bf4c1ab63323f38 to your computer and use it in GitHub Desktop.
Save tenthree/7dbda9ef8642bfe88bf4c1ab63323f38 to your computer and use it in GitHub Desktop.
simple rust server
use std::fs;
use std::io::{ Read, Write };
use std::net::{ TcpListener, TcpStream};
fn main() {
let server: TcpListener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in server.incoming() {
match stream {
Ok(mut stream) => {
router(stream)
},
Err(err) => {
println!("[Unable to connect] {}", err);
}
}
}
}
fn router(mut stream: TcpStream) {
let mut buf: [u8; 512] = [0; 512];
stream.read(&mut buf).unwrap();
println!("[request] {}", String::from_utf8_lossy(&buf[..]));
let body: String = fs::read_to_string("./public/index.html").unwrap();
let response: String = format!("HTTP/1.1 200 OK\r\n{}\r\n{}", "", body);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment