basic echo HTTP server
This commit is contained in:
1 parent
c86a898879
commit
d976eebbbc
11 files changed
+151
-45
No files matched your search
@@ -0,0 +1,69 @@
|
||||
use crate::error::CreddyError;
|
||||
use gpui_kit::AsyncApp;
|
||||
use http_body_util::Full;
|
||||
use hyper::{Request, Response, StatusCode};
|
||||
use hyper::body::{Incoming, Bytes};
|
||||
use hyper::service::service_fn;
|
||||
use hyper::server::conn::http1;
|
||||
use smol::Timer;
|
||||
use smol::net::unix::{UnixListener, UnixStream};
|
||||
use smol_hyper::rt::FuturesIo;
|
||||
use rustix::net::sockopt::socket_peercred;
|
||||
use rustix::process::Pid;
|
||||
use std::convert::Infallible;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
|
||||
pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> {
|
||||
if path.exists() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
let listener = UnixListener::bind(path)
|
||||
.map_err(|_| CreddyError::SocketBind(path.to_string_lossy().into()))?;
|
||||
|
||||
app.spawn(async move |app| {
|
||||
loop {
|
||||
let (stream, pid) = match accept(&listener).await {
|
||||
Ok((stream, pid)) => (stream, pid),
|
||||
Err(e) => {
|
||||
eprintln!("Error accepting connection: {e}");
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
app.spawn(async move |app| {
|
||||
let adapter = FuturesIo::new(stream);
|
||||
let service = service_fn(|req| handle(req, pid, app.clone()));
|
||||
let conn = http1::Builder::new().serve_connection(adapter, service);
|
||||
if let Err(e) = conn.await {
|
||||
eprintln!("Error serving connection: {e}")
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
}).detach();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
// pid() never returns None on Linux
|
||||
let pid = socket_peercred(&stream)?.pid;
|
||||
Ok((stream, pid))
|
||||
}
|
||||
|
||||
|
||||
async fn handle(req: Request<Incoming>, pid: Pid, app: AsyncApp) -> Result<Response<Full<Bytes>>, Infallible> {
|
||||
Ok(Response::new(Full::new(Bytes::from("hello world"))))
|
||||
}
|
||||
|
||||
fn text(status: StatusCode, body: &'static str) -> Response<Full<Bytes>> {
|
||||
let mut response = Response::new(Full::new(Bytes::from(body)));
|
||||
*response.status_mut() = status;
|
||||
response
|
||||
}
|
||||
Reference in new issue
Block a user