mirror of https://github.com/smol-rs/smol
Add async-h1 example
This commit is contained in:
parent
ea68616626
commit
d77f804ea0
|
@ -30,8 +30,11 @@ nix = "0.16.1"
|
|||
wepoll-binding = "1.1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
async-h1 = "1.0.1"
|
||||
futures = { version = "0.3.3", default-features = false, features = ["std"] }
|
||||
http-types = "1.0.1"
|
||||
hyper = { version = "0.13", default-features = false }
|
||||
io-arc = "1.0.0"
|
||||
num_cpus = "1.12.0"
|
||||
pin-utils = "0.1.0-alpha.4"
|
||||
tokio = { version = "0.2", default-features = false, features = ["rt-threaded", "time", "macros"] }
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
use std::net::{TcpListener, TcpStream};
|
||||
|
||||
use futures::io;
|
||||
use http_types::{Response, StatusCode};
|
||||
use io_arc::IoArc;
|
||||
use smol::{Async, Task};
|
||||
|
||||
async fn serve(addr: String, stream: Async<TcpStream>) -> http_types::Result<()> {
|
||||
async_h1::accept(&addr, stream.clone(), |_req| async move {
|
||||
let mut res = Response::new(StatusCode::Ok);
|
||||
res.insert_header("Content-Type", "text/plain")?;
|
||||
res.set_body("Hello from async-h1!");
|
||||
Ok(res)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
// Create a thread pool.
|
||||
for _ in 0..num_cpus::get_physical().max(1) {
|
||||
std::thread::spawn(|| smol::run(futures::future::pending::<()>()));
|
||||
}
|
||||
|
||||
smol::block_on(async {
|
||||
let listener = Async::<TcpListener>::bind("127.0.0.1:8080")?;
|
||||
let addr = format!("http://{}", listener.get_ref().local_addr()?);
|
||||
println!("listening on {}", addr);
|
||||
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let stream = IoArc::new(stream);
|
||||
Task::spawn(serve(addr.clone(), stream)).unwrap().forget();
|
||||
}
|
||||
})
|
||||
}
|
|
@ -6,7 +6,7 @@ use hyper::{Body, Request, Response, Server};
|
|||
use smol::Async;
|
||||
|
||||
async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
|
||||
Ok(Response::new(Body::from("Hello World!")))
|
||||
Ok(Response::new(Body::from("Hello from hyper!")))
|
||||
}
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
|
|
Loading…
Reference in New Issue