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
#![allow(unused_assignments)]
use std::io;
use std::io::Read;
use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use tokio_http2::{Body, ContentType, ContentLength};
use mime_guess::guess_mime_type;
use mime::*;
#[derive(Debug)]
pub struct FileBody {
pub content_length: ContentLength,
pub content_type: ContentType,
pub ext: String,
pub body: Body,
}
impl FileBody {
pub fn new(content_length: ContentLength, content_type: ContentType, ext: String, body: Body) -> FileBody {
FileBody{ content_length: content_length, content_type: content_type, ext: ext, body: body }
}
}
pub fn read(path: &str) -> Result<FileBody, io::Error> {
let mut file = match File::open(path) {
Ok(file) => file,
Err(e) => {
println!("{:?}", e);
return Err(e);
}
};
let mut content_length: ContentLength = 0;
let path2 = Path::new(path);
let ext: String;
match path2.extension() {
Some(s) => ext = s.to_str().unwrap_or("").to_string(),
None => ext = "".to_string(),
}
let mime = guess_mime_type(path2);
let content_type_string = mime.to_string();
let content_type: &str = &content_type_string;
let mut body = Body::new();
match file.read_to_end(&mut body) {
Ok(len) => {
content_length = len as u64;
},
Err(e) => {
return Err(e);
}
}
Ok(FileBody::new(content_length, content_type.to_string(), ext, body))
}