Skip to content

Commit

Permalink
chore(deps): update exmaples with hyper v1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
fundon committed Nov 19, 2023
1 parent 267dc9d commit 1db30e7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 49 deletions.
7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ include = [
smallvec = "1.11.0"

[dev-dependencies]
bytes = "1"
actix-router = "0.5"
ntex-router = "0.5"
path-table = "1.0"
Expand All @@ -33,8 +34,10 @@ gonzales = "0.0.3-beta"
futures = "0.3"
rand = "0.8"
criterion = { version = "0.5", features = ["html_reports"] }
hyper = { version="0.14", features = ["full"] }
tokio = { version = "1", default-features = false, features = ["macros", "rt-multi-thread"] }
hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["tokio"] }
http-body-util = "0.1"
tokio = { version = "1", default-features = false, features = ["macros", "rt-multi-thread", "net"] }

[[bench]]
name = "bench"
Expand Down
101 changes: 54 additions & 47 deletions examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,47 @@
#![allow(unused_must_use)]

use std::{convert::Infallible, future::Future, pin::Pin, sync::Arc};
use std::{convert::Infallible, future::Future, net::SocketAddr, pin::Pin, sync::Arc};

use bytes::Bytes;
use http_body_util::Full;
use hyper::{
server::Server,
service::{make_service_fn, service_fn},
Body, Request, Response, StatusCode,
body::Incoming, server::conn::http1, service::service_fn, Request, Response, StatusCode,
};
use hyper_util::rt::TokioIo;
use path_tree::PathTree;
use tokio::net::TcpListener;

static NOT_FOUND: &[u8] = b"Not Found";

type Params = Vec<(String, String)>;
type Body = Full<Bytes>;

trait Handler: Send + Sync + 'static {
fn call<'a>(
&'a self,
req: Request<Body>,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'a>>;
}

impl<F, R> Handler for F
where
F: Send + Sync + 'static + Fn(Request<Body>) -> R,
R: Future<Output = Response<Body>> + Send + 'static,
F: Send + Sync + 'static + Fn(Request<Incoming>) -> R,
R: Future<Output = Response<Full<Bytes>>> + Send + 'static,
{
fn call<'a>(
&'a self,
req: Request<Body>,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'a>> {
let fut = (self)(req);
Box::pin(async move { fut.await })
}
}

async fn index(_: Request<Body>) -> Response<Body> {
async fn index(_: Request<Incoming>) -> Response<Body> {
Response::new(Body::from("Hello, Web!"))
}

async fn hello_world(req: Request<Body>) -> Response<Body> {
async fn hello_world(req: Request<Incoming>) -> Response<Body> {
let params = req.extensions().get::<Params>().unwrap();
let mut s = String::new();
s.push_str("Hello, World!\n");
Expand All @@ -48,7 +51,7 @@ async fn hello_world(req: Request<Body>) -> Response<Body> {
Response::new(Body::from(s))
}

async fn hello_user(req: Request<Body>) -> Response<Body> {
async fn hello_user(req: Request<Incoming>) -> Response<Body> {
let params = req.extensions().get::<Params>().unwrap();
let mut s = String::new();
s.push_str("Hello, ");
Expand All @@ -59,17 +62,19 @@ async fn hello_user(req: Request<Body>) -> Response<Body> {
Response::new(Body::from(s))
}

async fn hello_rust(_: Request<Body>) -> Response<Body> {
async fn hello_rust(_: Request<Incoming>) -> Response<Body> {
Response::new(Body::from("Hello, Rust!"))
}

async fn login(_req: Request<Body>) -> Response<Body> {
async fn login(_req: Request<Incoming>) -> Response<Body> {
Response::new(Body::from("I'm logined!"))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = ([127, 0, 0, 1], 3000).into();
let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();

let listener = TcpListener::bind(addr).await?;

// /
// ├── GET/ •0
Expand All @@ -87,40 +92,42 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

let tree = Arc::new(tree);

let make_service = make_service_fn(move |_| {
loop {
let (tcp, _) = listener.accept().await?;
let io = TokioIo::new(tcp);
let router = Arc::clone(&tree);

async move {
Ok::<_, Infallible>(service_fn(move |mut req| {
let router = router.clone();
let path = "/".to_owned() + req.method().as_str() + req.uri().path();

async move {
Ok::<_, Infallible>(match router.find(&path) {
Some((handler, route)) => {
let p = route
.params()
.iter()
.map(|p| (p.0.to_string(), p.1.to_string()))
.collect::<Params>();
req.extensions_mut().insert(p);
handler.call(req).await
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(
io,
service_fn(move |mut req| {
let router = router.clone();
let path = "/".to_owned() + req.method().as_str() + req.uri().path();

async move {
Ok::<_, Infallible>(match router.find(&path) {
Some((handler, route)) => {
let p = route
.params()
.iter()
.map(|p| (p.0.to_string(), p.1.to_string()))
.collect::<Params>();
req.extensions_mut().insert(p);
handler.call(req).await
}
None => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOT_FOUND.into())
.unwrap(),
})
}
None => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOT_FOUND.into())
.unwrap(),
})
}
}))
}
});

let server = Server::bind(&addr).serve(make_service);

println!("Listening on http://{addr}");

server.await?;

Ok(())
}),
)
.await
{
println!("Error serving connection: {:?}", err);
}
});
}
}

0 comments on commit 1db30e7

Please sign in to comment.