mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-26 00:00:23 +02:00
Update unix-domain-socket, listen-multiple-addrs, and testing examples (#2358)
This commit is contained in:
@@ -4,183 +4,136 @@
|
||||
//! cargo run -p example-unix-domain-socket
|
||||
//! ```
|
||||
|
||||
// TODO
|
||||
fn main() {
|
||||
eprint!("this example has not yet been updated to hyper 1.0");
|
||||
#[cfg(unix)]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
unix::server().await;
|
||||
}
|
||||
|
||||
// #[cfg(unix)]
|
||||
// #[tokio::main]
|
||||
// async fn main() {
|
||||
// unix::server().await;
|
||||
// }
|
||||
#[cfg(not(unix))]
|
||||
fn main() {
|
||||
println!("This example requires unix")
|
||||
}
|
||||
|
||||
// #[cfg(not(unix))]
|
||||
// fn main() {
|
||||
// println!("This example requires unix")
|
||||
// }
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::connect_info::{self, ConnectInfo},
|
||||
http::{Method, Request, StatusCode},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use http_body_util::BodyExt;
|
||||
use hyper::body::Incoming;
|
||||
use hyper_util::{
|
||||
rt::{TokioExecutor, TokioIo},
|
||||
server,
|
||||
};
|
||||
use std::{convert::Infallible, path::PathBuf, sync::Arc};
|
||||
use tokio::net::{unix::UCred, UnixListener, UnixStream};
|
||||
use tower::Service;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
// #[cfg(unix)]
|
||||
// mod unix {
|
||||
// use axum::{
|
||||
// body::Body,
|
||||
// extract::connect_info::{self, ConnectInfo},
|
||||
// http::{Method, Request, StatusCode, Uri},
|
||||
// routing::get,
|
||||
// Router,
|
||||
// };
|
||||
// use futures::ready;
|
||||
// use hyper::{
|
||||
// client::connect::{Connected, Connection},
|
||||
// server::accept::Accept,
|
||||
// };
|
||||
// use std::{
|
||||
// io,
|
||||
// path::PathBuf,
|
||||
// pin::Pin,
|
||||
// sync::Arc,
|
||||
// task::{Context, Poll},
|
||||
// };
|
||||
// use tokio::{
|
||||
// io::{AsyncRead, AsyncWrite},
|
||||
// net::{unix::UCred, UnixListener, UnixStream},
|
||||
// };
|
||||
// use tower::BoxError;
|
||||
// use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
pub async fn server() {
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "debug".into()),
|
||||
)
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
|
||||
// pub async fn server() {
|
||||
// tracing_subscriber::registry()
|
||||
// .with(
|
||||
// tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
// .unwrap_or_else(|_| "debug".into()),
|
||||
// )
|
||||
// .with(tracing_subscriber::fmt::layer())
|
||||
// .init();
|
||||
let path = PathBuf::from("/tmp/axum/helloworld");
|
||||
|
||||
// let path = PathBuf::from("/tmp/axum/helloworld");
|
||||
let _ = tokio::fs::remove_file(&path).await;
|
||||
tokio::fs::create_dir_all(path.parent().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// let _ = tokio::fs::remove_file(&path).await;
|
||||
// tokio::fs::create_dir_all(path.parent().unwrap())
|
||||
// .await
|
||||
// .unwrap();
|
||||
let uds = UnixListener::bind(path.clone()).unwrap();
|
||||
tokio::spawn(async move {
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
// let uds = UnixListener::bind(path.clone()).unwrap();
|
||||
// tokio::spawn(async {
|
||||
// let app = Router::new().route("/", get(handler));
|
||||
let mut make_service = app.into_make_service_with_connect_info::<UdsConnectInfo>();
|
||||
|
||||
// hyper::Server::builder(ServerAccept { uds })
|
||||
// .serve(app.into_make_service_with_connect_info::<UdsConnectInfo>())
|
||||
// .await
|
||||
// .unwrap();
|
||||
// });
|
||||
// See https://github.com/tokio-rs/axum/blob/main/examples/serve-with-hyper/src/main.rs for
|
||||
// more details about this setup
|
||||
loop {
|
||||
let (socket, _remote_addr) = uds.accept().await.unwrap();
|
||||
|
||||
// let connector = tower::service_fn(move |_: Uri| {
|
||||
// let path = path.clone();
|
||||
// Box::pin(async move {
|
||||
// let stream = UnixStream::connect(path).await?;
|
||||
// Ok::<_, io::Error>(ClientConnection { stream })
|
||||
// })
|
||||
// });
|
||||
// let client = hyper::Client::builder().build(connector);
|
||||
let tower_service = unwrap_infallible(make_service.call(&socket).await);
|
||||
|
||||
// let request = Request::builder()
|
||||
// .method(Method::GET)
|
||||
// .uri("http://uri-doesnt-matter.com")
|
||||
// .body(Body::empty())
|
||||
// .unwrap();
|
||||
tokio::spawn(async move {
|
||||
let socket = TokioIo::new(socket);
|
||||
|
||||
// let response = client.request(request).await.unwrap();
|
||||
let hyper_service =
|
||||
hyper::service::service_fn(move |request: Request<Incoming>| {
|
||||
tower_service.clone().call(request)
|
||||
});
|
||||
|
||||
// assert_eq!(response.status(), StatusCode::OK);
|
||||
if let Err(err) = server::conn::auto::Builder::new(TokioExecutor::new())
|
||||
.serve_connection_with_upgrades(socket, hyper_service)
|
||||
.await
|
||||
{
|
||||
eprintln!("failed to serve connection: {err:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
|
||||
// let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
// assert_eq!(body, "Hello, World!");
|
||||
// }
|
||||
let stream = TokioIo::new(UnixStream::connect(path).await.unwrap());
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
|
||||
tokio::task::spawn(async move {
|
||||
if let Err(err) = conn.await {
|
||||
println!("Connection failed: {:?}", err);
|
||||
}
|
||||
});
|
||||
|
||||
// async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
|
||||
// println!("new connection from `{:?}`", info);
|
||||
let request = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("http://uri-doesnt-matter.com")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
// "Hello, World!"
|
||||
// }
|
||||
let response = sender.send_request(request).await.unwrap();
|
||||
|
||||
// struct ServerAccept {
|
||||
// uds: UnixListener,
|
||||
// }
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
// impl Accept for ServerAccept {
|
||||
// type Conn = UnixStream;
|
||||
// type Error = BoxError;
|
||||
let body = response.collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
assert_eq!(body, "Hello, World!");
|
||||
}
|
||||
|
||||
// fn poll_accept(
|
||||
// self: Pin<&mut Self>,
|
||||
// cx: &mut Context<'_>,
|
||||
// ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
|
||||
// let (stream, _addr) = ready!(self.uds.poll_accept(cx))?;
|
||||
// Poll::Ready(Some(Ok(stream)))
|
||||
// }
|
||||
// }
|
||||
async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
|
||||
println!("new connection from `{:?}`", info);
|
||||
|
||||
// struct ClientConnection {
|
||||
// stream: UnixStream,
|
||||
// }
|
||||
"Hello, World!"
|
||||
}
|
||||
|
||||
// impl AsyncWrite for ClientConnection {
|
||||
// fn poll_write(
|
||||
// mut self: Pin<&mut Self>,
|
||||
// cx: &mut Context<'_>,
|
||||
// buf: &[u8],
|
||||
// ) -> Poll<Result<usize, io::Error>> {
|
||||
// Pin::new(&mut self.stream).poll_write(cx, buf)
|
||||
// }
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
struct UdsConnectInfo {
|
||||
peer_addr: Arc<tokio::net::unix::SocketAddr>,
|
||||
peer_cred: UCred,
|
||||
}
|
||||
|
||||
// fn poll_flush(
|
||||
// mut self: Pin<&mut Self>,
|
||||
// cx: &mut Context<'_>,
|
||||
// ) -> Poll<Result<(), io::Error>> {
|
||||
// Pin::new(&mut self.stream).poll_flush(cx)
|
||||
// }
|
||||
impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
|
||||
fn connect_info(target: &UnixStream) -> Self {
|
||||
let peer_addr = target.peer_addr().unwrap();
|
||||
let peer_cred = target.peer_cred().unwrap();
|
||||
|
||||
// fn poll_shutdown(
|
||||
// mut self: Pin<&mut Self>,
|
||||
// cx: &mut Context<'_>,
|
||||
// ) -> Poll<Result<(), io::Error>> {
|
||||
// Pin::new(&mut self.stream).poll_shutdown(cx)
|
||||
// }
|
||||
// }
|
||||
Self {
|
||||
peer_addr: Arc::new(peer_addr),
|
||||
peer_cred,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// impl AsyncRead for ClientConnection {
|
||||
// fn poll_read(
|
||||
// mut self: Pin<&mut Self>,
|
||||
// cx: &mut Context<'_>,
|
||||
// buf: &mut tokio::io::ReadBuf<'_>,
|
||||
// ) -> Poll<io::Result<()>> {
|
||||
// Pin::new(&mut self.stream).poll_read(cx, buf)
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Connection for ClientConnection {
|
||||
// fn connected(&self) -> Connected {
|
||||
// Connected::new()
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Clone, Debug)]
|
||||
// #[allow(dead_code)]
|
||||
// struct UdsConnectInfo {
|
||||
// peer_addr: Arc<tokio::net::unix::SocketAddr>,
|
||||
// peer_cred: UCred,
|
||||
// }
|
||||
|
||||
// impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
|
||||
// fn connect_info(target: &UnixStream) -> Self {
|
||||
// let peer_addr = target.peer_addr().unwrap();
|
||||
// let peer_cred = target.peer_cred().unwrap();
|
||||
|
||||
// Self {
|
||||
// peer_addr: Arc::new(peer_addr),
|
||||
// peer_cred,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
fn unwrap_infallible<T>(result: Result<T, Infallible>) -> T {
|
||||
match result {
|
||||
Ok(value) => value,
|
||||
Err(err) => match err {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user