Bläddra i källkod

the web server tutorial, starting out. it's not in the mainline docs, but it is in the nightlies, so some code may require changes to run under release

jmelesky 7 år sedan
förälder
incheckning
0367fd32ec
3 ändrade filer med 57 tillägg och 0 borttagningar
  1. 6 0
      helloweb/Cargo.toml
  2. 11 0
      helloweb/hello.html
  3. 40 0
      helloweb/src/main.rs

+ 6 - 0
helloweb/Cargo.toml

@@ -0,0 +1,6 @@
+[package]
+name = "helloweb"
+version = "0.1.0"
+authors = ["jmelesky <code@phaedrusdeinus.org>"]
+
+[dependencies]

+ 11 - 0
helloweb/hello.html

@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Ahoy!</title>
+  </head>
+  <body>
+    <h1>Hello!</h1>
+    <p>Hi, from John and Rust</p>
+  </body>
+</html>

+ 40 - 0
helloweb/src/main.rs

@@ -0,0 +1,40 @@
+
+use std::io::prelude::*;
+use std::net::TcpListener;
+use std::net::TcpStream;
+use std::fs::File;
+
+
+fn main() {
+    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
+
+    for stream in listener.incoming() {
+        let stream = stream.unwrap();
+
+        handle_connection(stream);
+    }
+}
+
+
+fn handle_connection(mut stream: TcpStream) {
+    // assuming that 512 bytes will be enough for most request sizes
+    // this would be more complicated otherwise
+    // also, this is declared on the stack
+    let mut buffer = [0;512];
+
+    stream.read(&mut buffer).unwrap();
+
+    // hey, i'm reading a file!
+    let mut file = File::open("hello.html").unwrap();
+
+    let mut contents = String::new();
+    file.read_to_string(&mut contents).unwrap();
+
+    // slap that into a response
+    let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
+
+    stream.write(response.as_bytes()).unwrap();
+    stream.flush().unwrap();
+
+    println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
+}