smol/examples/async-h1-server.rs

96 lines
3.2 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/
2020-04-28 11:09:59 +00:00
//! - https://localhost:8001/ (accept the security prompt in the browser)
2020-04-20 15:45:14 +00:00
//!
2020-04-28 11:09:59 +00:00
//! Refer to `README.md` to see how to the TLS certificate was generated.
2020-04-20 15:45:14 +00:00
2020-07-15 09:37:50 +00:00
use std::net::TcpListener;
2020-03-29 15:59:28 +00:00
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 http_types::{Request, Response, StatusCode};
2020-08-26 21:59:49 +00:00
use smol::{future, Async};
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);
2020-07-20 06:45:56 +00:00
res.insert_header("Content-Type", "text/plain");
2020-03-29 15:59:28 +00:00
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-07-15 09:37:50 +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 {
2020-07-15 09:37:50 +00:00
None => format!("http://{}", listener.get_ref().local_addr()?),
Some(_) => format!("https://{}", listener.get_ref().local_addr()?),
2020-04-01 19:40:27 +00:00
};
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?;
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-07-14 19:19:01 +00:00
let stream = async_dup::Arc::new(stream);
2020-08-26 21:59:49 +00:00
smol::spawn(async move {
2020-07-20 06:45:56 +00:00
if let Err(err) = async_h1::accept(stream, serve).await {
2020-04-29 18:42:48 +00:00
println!("Connection error: {:#?}", err);
}
})
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-28 11:09:59 +00:00
match tls.accept(stream).await {
Ok(stream) => {
2020-07-14 19:19:01 +00:00
let stream = async_dup::Arc::new(async_dup::Mutex::new(stream));
2020-08-26 21:59:49 +00:00
smol::spawn(async move {
2020-07-20 06:45:56 +00:00
if let Err(err) = async_h1::accept(stream, serve).await {
2020-04-29 18:42:48 +00:00
println!("Connection error: {:#?}", err);
}
})
2020-04-28 11:09:59 +00:00
}
Err(err) => {
println!("Failed to establish secure TLS connection: {:#?}", err);
continue;
}
}
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-29 18:42:48 +00:00
task.detach();
2020-04-01 19:40:27 +00:00
}
}
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.
let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?;
2020-04-06 20:19:54 +00:00
let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);
2020-04-20 15:45:14 +00:00
// Start HTTP and HTTPS servers.
2020-08-26 21:59:49 +00:00
smol::block_on(async {
2020-07-15 09:37:50 +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),
);
2020-08-26 21:59:49 +00:00
future::try_zip(http, https).await?;
2020-04-01 19:40:27 +00:00
Ok(())
2020-03-29 15:59:28 +00:00
})
}