Add unix feature

This adds several components:

- a unix compile-time crate feature which allows for a `serve_unix` method which serves over a unix socket
- an example that serves over a unix socket

Signed-off-by: Erik Hollensbe <git@hollensbe.org>
This commit is contained in:
Erik Hollensbe
2022-04-27 07:31:26 -07:00
parent 63595ae5f5
commit 1ac2b56efe
3 changed files with 63 additions and 0 deletions
+1
View File
@@ -25,3 +25,4 @@ env_logger = "^0.9"
default = ["logging"]
logging = ["log"]
tls = ["tokio-rustls", "webpki"]
unix = []
+30
View File
@@ -0,0 +1,30 @@
use std::path::PathBuf;
use ratpack::prelude::*;
async fn hello(
req: Request<Body>,
_resp: Option<Response<Body>>,
params: Params,
_app: App<(), NoState>,
_state: NoState,
) -> HTTPResult<NoState> {
let name = params.get("name").unwrap();
let bytes = Body::from(format!("hello, {}!\n", name));
return Ok((
req,
Some(Response::builder().status(200).body(bytes).unwrap()),
NoState {},
));
}
#[tokio::main]
async fn main() -> Result<(), ServerError> {
let mut app = App::new();
app.get("/:name", compose_handler!(hello));
app.serve_unix(PathBuf::from("/tmp/server.sock")).await?;
Ok(())
}
+32
View File
@@ -4,6 +4,11 @@ use http::{HeaderMap, Method, Request, Response, StatusCode};
use hyper::{server::conn::Http, service::service_fn, Body};
use tokio::{net::TcpListener, sync::Mutex};
#[cfg(feature = "unix")]
use std::path::PathBuf;
#[cfg(feature = "unix")]
use tokio::net::UnixListener;
use crate::{handler::Handler, router::Router, Error, ServerError, TransientState};
/// App is used to define application-level functionality and initialize the server. Routes are
@@ -182,6 +187,33 @@ impl<S: 'static + Clone + Send, T: TransientState + 'static + Clone + Send> App<
}
}
#[cfg(feature = "unix")]
pub async fn serve_unix(self, filename: PathBuf) -> Result<(), ServerError> {
let unix_listener = UnixListener::bind(filename)?;
loop {
let (stream, _) = unix_listener.accept().await?;
let s = self.clone();
let sfn = service_fn(move |req: Request<Body>| {
let s = s.clone();
async move { s.clone().dispatch(req).await }
});
tokio::task::spawn(async move {
if let Err(http_err) = Http::new()
.http1_keep_alive(true)
.serve_connection(stream, sfn)
.await
{
#[cfg(feature = "logging")]
log::error!("Error while serving HTTP connection: {}", http_err);
#[cfg(not(feature = "logging"))]
eprintln!("Error while serving HTTP connection: {}", http_err);
}
});
}
}
/// Start a TCP/HTTP server with tokio. Performs dispatch on an as-needed basis. This is a more
/// common path for users to start a server.
pub async fn serve(self, addr: &str) -> Result<(), ServerError> {