Skip to content

Commit

Permalink
add Server::try_bind
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tdryer authored Jan 12, 2025
1 parent 157a6f8 commit 4e74c71
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Server> {
let listener = std::net::TcpListener::bind(addr)?;

Ok(Server {
listener: Some(listener),
..Default::default()
}
})
}

/// Serve incoming connections with the provided service.
Expand Down

0 comments on commit 4e74c71

Please sign in to comment.