rusty_request/requests/
get.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::{
    io::{Read, Write},
    net::TcpStream,
    sync::{Arc, Mutex},
};

use http_scrap::Response;

use crate::Get;

impl<'get> Get<'get> {
    pub fn new(stream: &'get TcpStream) -> Self {
        let org_stream = Arc::new(Mutex::new(stream));
        let mut buffer = [0; 1024];
        let mut stream = org_stream.lock().unwrap();
        stream.read(&mut buffer);

        let response = String::from_utf8_lossy(&buffer);
        let path = Response::new(&response);

        let path = path.path();

        Get {
            stream: Arc::clone(&org_stream),
            path: path.to_string(),
            match_path: None,
            content: None,
        }
    }
    pub fn path(&self, path: &str) -> Self {
        Self {
            path: self.path.clone(),
            stream: self.stream.clone(),
            match_path: Some(path.to_string()),
            content: None,
        }
    }
    pub fn content(&self, content: &str) -> Self {
        Self {
            content: Some(content.to_string()),
            match_path: self.match_path.clone(),
            path: self.path.clone(),
            stream: self.stream.clone(),
        }
    }
    pub fn send(&self) -> () {
        let mut stream: std::sync::MutexGuard<'_, &TcpStream> = self.stream.lock().unwrap();
        // println!("m {:?}", self.match_path);
        let match_path = self.match_path.clone().unwrap();
        if self.path == match_path {
            match &self.content {
                Some(content) => {
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                        content.len(),
                        content
                    );
                    println!("{}", response);
                    stream.write_all(response.as_bytes());
                    stream.flush();
                }
                None => {}
            }
        }
    }
}