-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
send_file.rs
91 lines (74 loc) · 2.64 KB
/
send_file.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
85
86
87
88
89
90
91
#![deny(warnings)]
use std::net::SocketAddr;
use bytes::Bytes;
use futures_util::TryStreamExt;
use http_body_util::{combinators::BoxBody, BodyExt, Full, StreamBody};
use hyper::body::Frame;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, Result, StatusCode};
use tokio::{fs::File, net::TcpListener};
use tokio_util::io::ReaderStream;
#[path = "../benches/support/mod.rs"]
mod support;
use support::TokioIo;
static INDEX: &str = "examples/send_file_index.html";
static NOTFOUND: &[u8] = b"Not Found";
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
pretty_env_logger::init();
let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();
let listener = TcpListener::bind(addr).await?;
println!("Listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(response_examples))
.await
{
println!("Failed to serve connection: {:?}", err);
}
});
}
}
async fn response_examples(
req: Request<hyper::body::Incoming>,
) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => simple_file_send(INDEX).await,
(&Method::GET, "/no_file.html") => {
// Test what happens when file cannot be found
simple_file_send("this_file_should_not_exist.html").await
}
_ => Ok(not_found()),
}
}
/// HTTP status code 404
fn not_found() -> Response<BoxBody<Bytes, std::io::Error>> {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(NOTFOUND.into()).map_err(|e| match e {}).boxed())
.unwrap()
}
async fn simple_file_send(filename: &str) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
// Open file for reading
let file = File::open(filename).await;
if file.is_err() {
eprintln!("ERROR: Unable to open file.");
return Ok(not_found());
}
let file: File = file.unwrap();
// Wrap to a tokio_util::io::ReaderStream
let reader_stream = ReaderStream::new(file);
// Convert to http_body_util::BoxBody
let stream_body = StreamBody::new(reader_stream.map_ok(Frame::data));
let boxed_body = stream_body.boxed();
// Send response
let response = Response::builder()
.status(StatusCode::OK)
.body(boxed_body)
.unwrap();
Ok(response)
}