This commit is contained in:
2026-01-08 17:32:06 +01:00
commit 9fcdfbd762
7 changed files with 977 additions and 0 deletions

104
src/main.rs Normal file
View File

@@ -0,0 +1,104 @@
use std::net::{TcpListener, TcpStream};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use anyhow::Result;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::service::service_fn;
use hyper::{Request, Response};
use macro_rules_attribute::apply;
use smol::{future, io, prelude::*, Async, Executor};
use smol_hyper::rt::{FuturesIo, SmolTimer};
use smol_macros::main;
/// Serves a request and returns a response.
async fn serve(req: Request<Incoming>) -> Result<Response<Full<&'static [u8]>>> {
println!("Serving {}", req.uri());
Ok(Response::new(Full::new("Hello from hyper!".as_bytes())))
}
/// Handle a new client.
async fn handle_client(client: Async<TcpStream>) -> Result<()> {
// Wrap it in TLS if necessary.
let client = SmolStream::Plain(client);
// Build the server.
hyper::server::conn::http1::Builder::new()
.timer(SmolTimer::new())
.serve_connection(FuturesIo::new(client), service_fn(serve))
.await?;
Ok(())
}
/// Listens for incoming connections and serves them.
async fn listen(ex: &Arc<Executor<'static>>, listener: Async<TcpListener>) -> Result<()> {
// Format the full host address.
// println!("Listening on {}", host);
loop {
// Wait for a new client.
let (client, _) = listener.accept().await?;
// Spawn a task to handle this connection.
ex.spawn({
async move {
if let Err(e) = handle_client(client).await {
println!("Error while handling client: {}", e);
}
}
})
.detach();
}
}
#[apply(main!)]
async fn main(ex: &Arc<Executor<'static>>) -> Result<()> {
// Start HTTP and HTTPS servers.
let _ = listen(ex, Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?).await;
print!("mroew");
Ok(())
}
/// A TCP or TCP+TLS connection.
enum SmolStream {
Plain(Async<TcpStream>),
}
impl AsyncRead for SmolStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_read(cx, buf),
}
}
}
impl AsyncWrite for SmolStream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_write(cx, buf),
}
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_close(cx),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut *self {
Self::Plain(s) => Pin::new(s).poll_close(cx),
}
}
}