From 4e74c7173faac98f12b0d28ab45f7354c8961f8a Mon Sep 17 00:00:00 2001 From: Tom Dryer Date: Sat, 11 Jan 2025 22:07:26 -0800 Subject: [PATCH] add `Server::try_bind` Add `Server::try_bind` as an alternative to `bind` that returns an error instead of panicking on bind failure. This makes it possible to avoid panicking for common failures such as the address already being in use. --- src/server.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/server.rs b/src/server.rs index b0599c4..15b6ca6 100644 --- a/src/server.rs +++ b/src/server.rs @@ -165,12 +165,27 @@ impl Server { /// /// This method will panic if binding to the address fails. pub fn bind(addr: impl ToSocketAddrs) -> Server { - let listener = std::net::TcpListener::bind(addr).expect("failed to bind listener"); + Self::try_bind(addr).expect("failed to bind listener") + } - Server { + /// Binds a server to the provided address, returning an error on failure. + /// + /// ```no_run + /// use astra::Server; + /// use std::net::SocketAddr; + /// + /// let server = Server::try_bind("localhost:3000") + /// .expect("failed to bind listener"); + /// let server = Server::try_bind(SocketAddr::from(([127, 0, 0, 1], 3000))) + /// .expect("failed to bind listener"); + /// ``` + pub fn try_bind(addr: impl ToSocketAddrs) -> io::Result { + let listener = std::net::TcpListener::bind(addr)?; + + Ok(Server { listener: Some(listener), ..Default::default() - } + }) } /// Serve incoming connections with the provided service.