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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use std::{fs};
use std::fs::{remove_file};
use std::path::Path;
use chrono::{Utc};
use json::{JsonValue};
use log::info;
use crate::cors::Cors;


/// http请求
pub struct Http {
    cors: Cors,
}

impl Http {
    pub fn default(cors: Cors) -> Self {
        Self {
            cors: cors.clone(),
        }
    }
    pub fn handle(&mut self, header: JsonValue, mut body: JsonValue, fun: fn(request: JsonValue) -> (JsonValue, i32, String)) -> (bool, String) {

        // 判断是否检查请求
        if header["method"].as_str().unwrap() == "OPTIONS" {
            return (true, self._options());
        }
        // 检查是否是文件路径
        let file = format!("{}{}", header["public"], header["uri"].as_str().unwrap());

        if Path::new(file.as_str()).is_file() {
            return (true, self._file_html(file.as_str()));
        }
        body["header"] = header.clone();
        let (contents, code, content_type) = fun(body.clone());
        // // 清理temp临时缓存文件
        for (_, files) in body["files"].entries() {
            for item in files.members() {
                if Path::new(item["temp"].as_str().unwrap()).is_file() {
                    match remove_file(item["temp"].as_str().unwrap()) {
                        Ok(_) => true,
                        Err(_) => {
                            info!("删除文件失败:{}", item["temp"]);
                            false
                        }
                    };
                }
            }
        }
        (true, self._write(contents, code, content_type))
    }
    /// 读取文件返回
    fn _file_html(&mut self, filename: &str) -> String {
        let name: Vec<&str> = filename.split("/").collect();
        let name = name[name.len() - 1];
        let sufxx: Vec<&str> = filename.split(".").collect();
        let sufxx = sufxx[sufxx.len() - 1];

        let file = fs::read(filename).unwrap();
        let contents = unsafe { String::from_utf8_unchecked(file) };

        let crlf = "\r\n";
        let status = format!("HTTP/1.1 200 OK{}", crlf);


        let date = format!("Date: {}{}", Utc::now().format("%a %d %b %Y %H:%M:%S GMT").to_string(), crlf);
        let server = format!("Server: Rust{}", crlf);
        let content_length = format!("Content-Length: {}{}", contents.len(), crlf);
        let content_disposition = match sufxx {
            "html" => {
                format!("")
            }
            _ => {
                format!("Content-Disposition: attachment; filename={}{}", name, crlf)
            }
        };
        let content_type = match sufxx {
            "jpg" => {
                format!("content-type:image/jpg{}", crlf)
            }
            "png" => {
                format!("content-type:image/png{}", crlf)
            }
            "bmp" => {
                format!("content-type:image/bmp{}", crlf)
            }
            "jpeg" => {
                format!("content-type:image/jpeg{}", crlf)
            }
            "svg" => {
                format!("content-type:image/svg{}", crlf)
            }
            "webp" => {
                format!("content-type:image/webp{}", crlf)
            }
            "ico" => {
                format!("content-type:image/ico{}", crlf)
            }
            "gif" => {
                format!("content-type:image/gif{}", crlf)
            }
            _ => {
                format!("content-type: text/plain;charset=utf-8{}", crlf)
            }
        };
        let response = format!("{}{}{}{}{}{}{}{}", status, date, server, content_disposition, content_type, content_length, crlf, contents);
        // self.stream.write_all(response.as_bytes()).unwrap();
        // self.stream.flush().unwrap();
        response
    }
    fn _options(&mut self) -> String {
        let crlf = "\r\n";
        let status = format!("HTTP/1.1 200 OK{}", crlf);
        let date = format!("Date: {}{}", Utc::now().format("%a %d %b %Y %H:%M:%S GMT").to_string(), crlf);
        let server = format!("Server: Rust{}", crlf);
        let allow_origin = format!("Access-Control-Allow-Origin: {}{}", self.cors.allow_origin, crlf);
        let allow_methods = format!("Access-Control-Allow-Methods: {}{}", self.cors.allow_methods, crlf);
        let allow_headers = format!("Access-Control-Allow-Headers: {}{}", self.cors.allow_headers, crlf);
        let max_age = format!("Access-Control-Max-Age: {}{}", self.cors.max_age, crlf);
        let allow_credentials = format!("Access-Control-Allow-Credentials: {}{}", self.cors.allow_credentials, crlf);

        let response = format!("{}{}{}{}{}{}{}{}{}",
                               status, date, server,
                               allow_origin,
                               allow_methods,
                               allow_credentials,
                               max_age,
                               allow_headers,
                               crlf);
        // self.stream.write(response.as_bytes()).unwrap();
        // self.stream.flush().unwrap();
        response
    }
    /// 将响应写出到流
    fn _write(&mut self, contents: JsonValue, code: i32, content_type: String) -> String {
        let crlf = "\r\n";
        let status = format!("HTTP/1.1 {} {}{}", code, "OK", crlf);
        let content_type = {
            match content_type.as_str() {
                "json" => {
                    format!("content-type: application/json;charset=utf-8{}", crlf)
                }
                _ => {
                    format!("content-type: text/html;charset=utf-8{}", crlf)
                }
            }
        };
        let access_control_allow_origin = format!("Access-Control-Allow-Origin: *{}", crlf);
        let content_length = format!("Content-Length: {}{}", contents.to_string().as_bytes().len(), crlf);
        let response = format!("{}{}{}{}{}{}", status, content_type, access_control_allow_origin, content_length, crlf, contents);
        response
    }
}