Created
January 24, 2020 15:47
-
-
Save rust-play/3e8919923b400617aa8c74b6909d4be8 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::convert::Infallible; | |
use std::net::SocketAddr; | |
use hyper::{Body, Request, Response, Server, StatusCode}; | |
use hyper::service::{make_service_fn, service_fn}; | |
#[tokio::main] | |
async fn main() { | |
let addr = SocketAddr::from(([127, 0, 0, 1], 3030)); | |
let make_svc = make_service_fn(|_conn| async { | |
Ok::<_, Infallible>(service_fn(handle)) | |
}); | |
let server = Server::bind(&addr).serve(make_svc); | |
if let Err(e) = server.await { | |
eprintln!("server error: {}", e); | |
} | |
} | |
async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> { | |
println!("Request: {:#?}", req); | |
let mut parts = req.uri().path().split('/').filter(|p| p.len() > 0); | |
match parts.next() { | |
Some("hello") => { | |
if let Some(number) = parts.next() { | |
if let Some(name) = parts.next() { | |
if let None = parts.next() { // ensure it was the last part of the path | |
return Ok(handle_hello(&req, number, name)); | |
} | |
} | |
} | |
} | |
Some("bonjour") => { | |
if let Some(first_part) = parts.next() { | |
if let Some(second_part) = parts.next() { | |
return Ok(handle_bonjour(Some(first_part), second_part)); | |
} else { | |
return Ok(handle_bonjour(None, first_part)); | |
} | |
} | |
} | |
_ => {} | |
}; | |
return Ok(Response::builder() | |
.status(StatusCode::NOT_FOUND) | |
.body(Body::from(format!("Nothing found at {}", req.uri().path()))) | |
.unwrap()); | |
} | |
fn handle_hello(req: &Request<Body>, number: &str, name: &str) -> Response<Body> { | |
let number: u32 = match number.parse() { | |
Ok(n) => n, | |
Err(_) => { | |
return Response::builder() | |
.status(StatusCode::BAD_REQUEST) | |
.header("x-you-failed", "oh so much") | |
.body(Body::from(format!("/hello/number/name : number needs to be an unsigned 32-bit integer value"))) | |
.unwrap(); | |
} | |
}; | |
let user_agent: &str = req.headers().get("User-Agent").map(|v| v.to_str().unwrap_or("")).unwrap_or(""); | |
return Response::builder() | |
.status(StatusCode::OK) | |
.body(Body::from(format!("Hello, number {}: {} from {}", number, name, user_agent))) | |
.unwrap(); | |
} | |
fn handle_bonjour(title: Option<&str>, name: &str) -> Response<Body> { | |
Response::builder() | |
.status(StatusCode::OK) | |
.body(Body::from(match title { | |
Some(title) => format!("Bonjour, {} {}", title, name), | |
None => format!("Bonjour, {}", name), | |
})).unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment