- Open the Cargo.toml file that has been generated for you
- Under [dependencies], if you didn't do so in the last recipe, add the following lines:
futures = "0.1.18"
hyper = "0.11.21"
- If you want, you can go to futures' (https://crates.io/crates/futures) and hyper's (https://crates.io/crates/hyper) crates.io pages to check for the newest version and use that one instead
- In the folder src/bin, create a file called echo_server_with_routing.rs
- Add the following code and run it with cargo run --bin echo_server_with_routing:
1 extern crate hyper; 2 3 use hyper::{Method, StatusCode}; 4 use hyper::server::{const_service, service_fn, Http, Request,
Response}; 5 use hyper::header::{ContentLength, ContentType}; 6 use std::net::SocketAddr; 7 8 fn main() { 9 let addr = "[::1]:3000".parse().expect("Failed to parse
address"); 10 run_echo_server(&addr).expect("Failed to run web server"); 11 } 12 13 fn run_echo_server(addr: &SocketAddr) -> Result<(),
hyper::Error> { 14 let echo_service = const_service(service_fn(|req: Request| { 15 // An easy way to implement routing is 16 // to simply match the request's path 17 match (req.method(), req.path()) { 18 (&Method::Get, "/") => handle_root(), 19 (&Method::Post, "/echo") => handle_echo(req), 20 _ => handle_not_found(), 21 } 22 })); 23 24 let server = Http::new().bind(addr, echo_service)?; 25 server.run() 26 }
The functions are handling the routes:
28 type ResponseResult = Result<Response, hyper::Error>; 29 fn handle_root() -> ResponseResult { 30 const MSG: &str = "Try doing a POST at /echo"; 31 Ok(Response::new() 32 .with_header(ContentType::plaintext()) 33 .with_header(ContentLength(MSG.len() as u64)) 34 .with_body(MSG)) 35 } 36 37 fn handle_echo(req: Request) -> ResponseResult { 38 // The echoing is implemented by setting the response's 39 // body to the request's body 40 Ok(Response::new().with_body(req.body())) 41 } 42 43 fn handle_not_found() -> ResponseResult { 44 // Return a 404 for every unsupported route 45 Ok(Response::new().with_status(StatusCode::NotFound)) 46 }