Updated example for new Handler trait
This introduces a bit of complexity to the example, mainly the use of the try_continue! macro for dealing with errors, but I think this is an appropriate trade-off as users of this library are likely to be framework authors instead of end users.
This commit is contained in:
@@ -1,38 +1,55 @@
|
|||||||
|
#![feature(macro_rules)]
|
||||||
|
|
||||||
extern crate hyper;
|
extern crate hyper;
|
||||||
extern crate debug;
|
extern crate debug;
|
||||||
|
|
||||||
use std::io::{IoResult};
|
|
||||||
use std::io::util::copy;
|
use std::io::util::copy;
|
||||||
use std::io::net::ip::Ipv4Addr;
|
use std::io::net::ip::Ipv4Addr;
|
||||||
|
|
||||||
use hyper::{Get, Post};
|
use hyper::{Get, Post};
|
||||||
use hyper::server::{Server, Handler, Request, Response};
|
use hyper::server::{Server, Handler, Incoming};
|
||||||
use hyper::header::ContentLength;
|
use hyper::header::ContentLength;
|
||||||
|
|
||||||
struct Echo;
|
struct Echo;
|
||||||
|
|
||||||
|
macro_rules! try_continue(
|
||||||
|
($e:expr) => {{
|
||||||
|
match $e {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => { println!("Error: {}", e); continue; }
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
impl Handler for Echo {
|
impl Handler for Echo {
|
||||||
fn handle(&mut self, mut req: Request, mut res: Response) -> IoResult<()> {
|
fn handle(self, mut incoming: Incoming) {
|
||||||
match req.uri {
|
for (mut req, mut res) in incoming {
|
||||||
hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
|
match req.uri {
|
||||||
(&Get, "/") | (&Get, "/echo") => {
|
hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
|
||||||
let out = b"Try POST /echo";
|
(&Get, "/") | (&Get, "/echo") => {
|
||||||
|
let out = b"Try POST /echo";
|
||||||
|
|
||||||
res.headers.set(ContentLength(out.len()));
|
res.headers.set(ContentLength(out.len()));
|
||||||
try!(res.write(out));
|
try_continue!(res.write(out));
|
||||||
return res.end();
|
try_continue!(res.end());
|
||||||
|
continue;
|
||||||
|
},
|
||||||
|
(&Post, "/echo") => (), // fall through, fighting mutable borrows
|
||||||
|
_ => {
|
||||||
|
res.status = hyper::status::NotFound;
|
||||||
|
try_continue!(res.end());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
(&Post, "/echo") => (), // fall through, fighting mutable borrows
|
|
||||||
_ => {
|
_ => {
|
||||||
res.status = hyper::status::NotFound;
|
try_continue!(res.end());
|
||||||
return res.end();
|
continue;
|
||||||
}
|
}
|
||||||
},
|
};
|
||||||
_ => return res.end()
|
|
||||||
};
|
|
||||||
|
|
||||||
try!(copy(&mut req, &mut res));
|
try_continue!(copy(&mut req, &mut res));
|
||||||
res.end()
|
try_continue!(res.end());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user