Skip to content
Permalink
Browse files

Part 1

  • Loading branch information...
levidyrek committed May 11, 2019
0 parents commit 8de6e221b40aba54442d2ae9980a41bae349a237
Showing with 198 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +86 −0 Cargo.lock
  3. +9 −0 Cargo.toml
  4. +5 −0 README.md
  5. +67 −0 src/lib.rs
  6. +29 −0 src/main.rs
@@ -0,0 +1,2 @@
/target
**/*.rs.bk

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
@@ -0,0 +1,9 @@
[package]
name = "rust_http_server"
version = "0.1.0"
authors = ["Levi Payne <levi.dyrek@gmail.com>"]
edition = "2018"

[dependencies]
bufstream = "0.1.4"
chrono = "0.4"
@@ -0,0 +1,5 @@
# Creating a Static HTTP Server with Rust

This is example code for a blog post about Creating a Static HTTP Server with Rust.

Read Part 1 here: [Creating a Static HTTP Server with Rust - Part 1](http://concisecoder.io/2019/05/11/creating-a-static-http-server-with-rust-part-1/)
@@ -0,0 +1,67 @@
use std::io;
use std::io::prelude::*;
use std::net::TcpStream;

use bufstream::BufStream;
use chrono::prelude::*;


struct Request {
http_version: String,
method: String,
path: String,
time: DateTime<Local>,
}

pub fn handle_client(stream: TcpStream) -> io::Result<()> {
let mut buf = BufStream::new(stream);
let mut request_line = String::new();

// Get only the first line of the request, since this
// is a static HTTP 1.0 server.
buf.read_line(&mut request_line)?;
match parse_request(&mut request_line) {
Ok(request) => {
log_request(&request);
},
Err(()) => {
println!("Bad request: {}", &request_line);
},
}

Ok(())
}

fn parse_request(request: &mut String) -> Result<Request, ()> {
let mut parts = request.split(" ");
let method = match parts.next() {
Some(method) => method.trim().to_string(),
None => return Err(()),
};
let path = match parts.next() {
Some(path) => path.trim().to_string(),
None => return Err(()),
};
let http_version = match parts.next() {
Some(version) => version.trim().to_string(),
None => return Err(()),
};
let time = Local::now();

Ok( Request {
http_version: http_version,
method: method,
path: path,
time: time
} )
}

fn log_request(request: &Request) {
println!(
"[{}] \"{} {} {}\"",
request.time,
request.method,
request.path,
request.http_version,
);
}
@@ -0,0 +1,29 @@
use std::io;
use std::net::TcpListener;

use rust_http_server;

extern crate chrono;


fn main() -> io::Result<()> {
println!("Starting server...");

let listener = TcpListener::bind("127.0.0.1:8001")?;

println!("Server started!");

for stream in listener.incoming() {
match stream {
Ok(stream) => {
match rust_http_server::handle_client(stream) {
Err(e) => eprintln!("Error handling client: {}", e),
_ => (),
}
},
Err(e) => eprintln!("Connection failed: {}", e),
}
}

Ok(())
}

0 comments on commit 8de6e22

Please sign in to comment.
You can’t perform that action at this time.