Browse Source

Preuve de concept : serveur web multithread

nas 1 year ago
parent
commit
9bd8a0b14c
3 changed files with 69 additions and 0 deletions
  1. 11
    0
      pages/404.html
  2. 11
    0
      pages/hello.html
  3. 47
    0
      src/main.rs

+ 11
- 0
pages/404.html View File

@@ -0,0 +1,11 @@
1
+<!DOCTYPE html>
2
+<html lang="en">
3
+  <head>
4
+    <meta charset="utf-8">
5
+    <title>Hello!</title>
6
+  </head>
7
+  <body>
8
+    <h1>404</h1>
9
+    <p>Not Found</p>
10
+  </body>
11
+</html>

+ 11
- 0
pages/hello.html View File

@@ -0,0 +1,11 @@
1
+<!DOCTYPE html>
2
+<html lang="en">
3
+  <head>
4
+    <meta charset="utf-8">
5
+    <title>Hello!</title>
6
+  </head>
7
+  <body>
8
+    <h1>Hello!</h1>
9
+    <p>Hi from Rust</p>
10
+  </body>
11
+</html>

+ 47
- 0
src/main.rs View File

@@ -2,6 +2,51 @@ use reqwest;
2 2
 use reqwest::header;
3 3
 use std::error::Error;
4 4
 
5
+use std::{
6
+    fs,
7
+    io::{prelude::*, BufReader},
8
+    net::{TcpListener, TcpStream},
9
+    thread,
10
+    time::Duration,
11
+};
12
+
13
+fn handle_connection(mut stream: TcpStream) {
14
+    let buf_reader = BufReader::new(&mut stream);
15
+    let request_line = buf_reader.lines().next().unwrap().unwrap();
16
+
17
+    let (status_line, filename) = match &request_line[..] {
18
+        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "pages/hello.html"),
19
+        "GET /sleep HTTP/1.1" => {
20
+            thread::sleep(Duration::from_secs(5));
21
+            ("HTTP/1.1 200 OK", "pages/hello.html")
22
+        }
23
+        _ => ("HTTP/1.1 404 NOT FOUND", "pages/404.html"),
24
+    };
25
+
26
+    // --snip--
27
+
28
+    let contents = fs::read_to_string(filename).unwrap();
29
+    let length = contents.len();
30
+
31
+    let response =
32
+        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
33
+
34
+    stream.write_all(response.as_bytes()).unwrap();
35
+}
36
+
37
+fn webserver() {
38
+    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
39
+    let pool = ThreadPool::new(4);
40
+
41
+    for stream in listener.incoming() {
42
+        let stream = stream.unwrap();
43
+
44
+        pool.execute(|| {
45
+            handle_connection(stream);
46
+        });
47
+    }
48
+}
49
+
5 50
 #[tokio::main]
6 51
 async fn main() -> Result<(), Box<dyn Error>> {
7 52
     let server = "https://redmine.cli.coop";//https://api.coinstats.app/public/v1/coins/dogecoin
@@ -22,5 +67,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
22 67
         .text()
23 68
         .await?;
24 69
     println!("{:}", doge);
70
+
71
+    webserver();
25 72
     Ok(())
26 73
 }

Loading…
Cancel
Save