smol/examples/async-h1-server.rs

88 lines
2.9 KiB
Rust
Raw Normal View History

2020-04-20 15:45:14 +00:00
//! An HTTP+TLS server based on `async-h1` and `async-native-tls`.
//!
//! Run with:
//!
//! ```
//! cargo run --example async-h1-server
//! ```
//!
//! Open in the browser any of these addresses:
//!
//! - http://localhost:8000/
//! - https://localhost:8001/ (you'll need to import the TLS certificate first!)
//!
//! Refer to `README.md` to see how to import or generate the TLS certificate.
2020-03-29 15:59:28 +00:00
use std::net::TcpListener;
use std::thread;
use anyhow::Result;
2020-04-06 20:19:54 +00:00
use async_native_tls::{Identity, TlsAcceptor};
2020-03-29 15:59:28 +00:00
use futures::prelude::*;
use http_types::{Request, Response, StatusCode};
2020-04-21 15:51:07 +00:00
use piper::{Arc, Mutex};
2020-04-06 20:19:54 +00:00
use smol::{Async, Task};
2020-03-29 15:59:28 +00:00
/// Serves a request and returns a response.
async fn serve(req: Request) -> http_types::Result<Response> {
println!("Serving {}", req.url());
2020-04-01 19:40:27 +00:00
2020-03-29 15:59:28 +00:00
let mut res = Response::new(StatusCode::Ok);
res.insert_header("Content-Type", "text/plain")?;
res.set_body("Hello from async-h1!");
Ok(res)
}
2020-04-20 15:45:14 +00:00
/// Listens for incoming connections and serves them.
2020-04-01 19:40:27 +00:00
async fn listen(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Result<()> {
2020-04-20 15:45:14 +00:00
// Format the full host address.
2020-04-01 19:40:27 +00:00
let host = match &tls {
None => format!("http://{}", listener.get_ref().local_addr()?),
Some(_) => format!("https://{}", listener.get_ref().local_addr()?),
};
println!("Listening on {}", host);
loop {
2020-04-20 15:45:14 +00:00
// Accept the next connection.
2020-04-01 19:40:27 +00:00
let (stream, _) = listener.accept().await?;
let host = host.clone();
2020-04-20 15:45:14 +00:00
// Spawn a background task serving this connection.
2020-04-01 19:40:27 +00:00
let task = match &tls {
None => {
2020-04-21 15:51:07 +00:00
let stream = Arc::new(stream);
2020-04-05 11:50:09 +00:00
Task::spawn(async move { async_h1::accept(&host, stream, serve).await })
2020-04-01 19:40:27 +00:00
}
Some(tls) => {
2020-04-20 15:45:14 +00:00
// In case of HTTPS, establish a secure TLS connection first.
2020-04-01 19:40:27 +00:00
let stream = tls.accept(stream).await?;
2020-04-21 15:51:07 +00:00
let stream = Arc::new(Mutex::new(stream));
2020-04-05 11:50:09 +00:00
Task::spawn(async move { async_h1::accept(&host, stream, serve).await })
2020-04-01 19:40:27 +00:00
}
};
2020-04-20 15:45:14 +00:00
// Detach the task to let it run in the background.
2020-04-01 19:40:27 +00:00
task.unwrap().detach();
}
}
2020-03-29 15:59:28 +00:00
fn main() -> Result<()> {
2020-04-20 15:45:14 +00:00
// Initialize TLS with the local certificate, private key, and password.
2020-04-06 20:19:54 +00:00
let identity = Identity::from_pkcs12(include_bytes!("../identity.pfx"), "password")?;
let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);
2020-04-20 15:45:14 +00:00
// Create an executor thread pool.
2020-04-12 13:02:42 +00:00
let num_threads = num_cpus::get().max(1);
2020-03-29 15:59:28 +00:00
for _ in 0..num_threads {
thread::spawn(|| smol::run(future::pending::<()>()));
}
2020-04-20 15:45:14 +00:00
// Start HTTP and HTTPS servers.
2020-03-29 15:59:28 +00:00
smol::block_on(async {
2020-04-01 19:40:27 +00:00
let http = listen(Async::<TcpListener>::bind("127.0.0.1:8000")?, None);
let https = listen(Async::<TcpListener>::bind("127.0.0.1:8001")?, Some(tls));
future::try_join(http, https).await?;
Ok(())
2020-03-29 15:59:28 +00:00
})
}