http_scrap/
lib.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::{error::Error, io};

pub struct Response<'a> {
    response: &'a str,
}

impl<'a> Response<'a> {
    pub fn new(response: &str) -> Response {
        // * gets the response from client in lossy format
        //! lossy format is used to convert the binary to readable string
        let parse = Response { response: response };
        Response {
            response: parse.response,
        }
    }
    pub fn method(&self) -> &str {
        //* extract the methods like GET, POST, PUT, DELETE */
        //* splits the response and get the 0th index element */
        //*  */
        let method = self.response.split(" ").nth(0);
        match method {
            Some(method) => method,
            None => "path not found",
        }
    }
    pub fn path(&self) -> &str {
        let path = self.response.split(" ").nth(1);
        // println!("{}", path);
        match path {
            Some(path) => path,
            None => "path not found",
        }
    }
    pub fn encoding_type(&self) -> Vec<&str> {
        let responses = self.response.find("Accept-Encoding").unwrap();
        let accept: Vec<&str> = self.response[responses..]
            .trim_end_matches("\0")
            .trim_end_matches("\r\n")
            .split("\r\n")
            .nth(0)
            .unwrap()
            .split(":")
            .nth(1)
            .unwrap()
            .split(",")
            .collect();
        accept
    }
    pub fn content(&self) -> &str {
        let content = self
            .response
            .find("\r\n\r\n")
            .unwrap_or(self.response.len());
        let response = self.response[content..].trim().trim_end_matches("\0");
        response
    }
    pub fn token(&self) -> &str {
        match self.response.find("Authorization : Bearer") {
            Some(size) => {
                let response = self.response[size..].trim().trim_end_matches("\r\n\r\n");
                response
            }
            None => "Invalid token",
        }
    }
    pub fn cookie(&self) -> Result<&str, Box<dyn Error>> {
        // println!("{}", self.response);
        match self.response.find("Cookie: ") {
            Some(size) => {
                let size = size + "Cookie :".len();
                let cookie = self.response[size..]
                    .trim()
                    .trim_end_matches("\r\n\r\n")
                    .trim_end_matches("\0");
                println!("{:?}", cookie);
                Ok(cookie)
            }
            None => Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidData,
                "Cookie Not found",
            ))),
        }
    }
}