This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathhyper_server.rs
51 lines (46 loc) · 1.68 KB
/
hyper_server.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
extern crate hyper;
extern crate multipart;
use std::io;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
use hyper::server::response::Response as HyperResponse;
use multipart::server::hyper::{Switch, MultipartHandler, HyperRequest};
use multipart::server::{Multipart, Entries, SaveResult};
use multipart::mock::StdoutTee;
struct NonMultipart;
impl Handler for NonMultipart {
fn handle(&self, _: Request, mut res: Response) {
*res.status_mut() = StatusCode::ImATeapot;
res.send(b"Please send a multipart req :(\n").unwrap();
}
}
struct EchoMultipart;
impl MultipartHandler for EchoMultipart {
fn handle_multipart(&self, mut multipart: Multipart<HyperRequest>, res: HyperResponse) {
match multipart.save().temp() {
SaveResult::Full(entries) => process_entries(res, entries).unwrap(),
SaveResult::Partial(entries, error) => {
println!("Errors saving multipart:\n{:?}", error);
process_entries(res, entries.into()).unwrap();
}
SaveResult::Error(error) => {
println!("Errors saving multipart:\n{:?}", error);
res.send(format!("An error occurred {}", error).as_bytes()).unwrap();
}
};
}
}
fn process_entries(res: HyperResponse, entries: Entries) -> io::Result<()> {
let mut res = res.start()?;
let stdout = io::stdout();
let out = StdoutTee::new(&mut res, &stdout);
entries.write_debug(out)
}
fn main() {
println!("Listening on 0.0.0.0:3333");
Server::http("0.0.0.0:3333").unwrap().handle(
Switch::new(
NonMultipart,
EchoMultipart
)).unwrap();
}