Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Last active February 5, 2017 19:57
Show Gist options
  • Save jbenner-radham/6bc22f923d42438ff6bf5668d9e0050e to your computer and use it in GitHub Desktop.
Save jbenner-radham/6bc22f923d42438ff6bf5668d9e0050e to your computer and use it in GitHub Desktop.
A simple "hello world" web server written in Rust.
[package]
name = "simple-web-server"
version = "0.1.0"
authors = ["James Benner <[email protected]>"]
[dependencies]
time = "0.1"
extern crate time;
use std::io::Write;
use std::net::TcpListener;
fn main() {
// Bind allows us to create a connection on the port
// and gets it ready to accept connections.
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
// The listener's accept method waits or 'blocks' until
// we have a connection and then returns a new TcpStream
// that we can read and write data to.
let mut stream = listener.accept().unwrap().0;
let message = "Hello, World!";
let format = "%a, %d %b %Y %T GMT";
let time = time::now_utc();
let response = format!("HTTP/1.1 200 OK\r\n\
Date: {}\r\n\
Content-Type: text/html; charset=utf-8\r\n\
Content-Length: {}\r\n\
\r\n\
{}",
time::strftime(format, &time).unwrap(),
message.len(),
message);
let _ = stream.write(response.as_bytes());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment