-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_macros.rs
31 lines (27 loc) · 1.12 KB
/
helper_macros.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
//! A simple demonstration how iron's helper macros make e.g. IO-intensive code easier to write.
#[macro_use] extern crate iron;
use std::io;
use std::fs;
use iron::prelude::*;
use iron::status;
use iron::method;
fn main() {
Iron::new(|req: &mut Request| {
Ok(match req.method {
method::Get => {
// It's not a server error if the file doesn't exist yet. Therefore we use
// `iexpect`, to return Ok(...) instead of Err(...) if the file doesn't exist.
let f = iexpect!(fs::File::open("foo.txt").ok(), (status::Ok, ""));
Response::with((status::Ok, f))
},
method::Put => {
// If creating the file fails, something is messed up on our side. We probably want
// to log the error, so we use `itry` instead of `iexpect`.
let mut f = itry!(fs::File::create("foo.txt"));
itry!(io::copy(&mut req.body, &mut f));
Response::with(status::Created)
},
_ => Response::with(status::BadRequest)
})
}).http("localhost:3000").unwrap();
}