Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add means to find the socket address for Serve and WithGracefulShutdown #2879

Closed
JosephLenton opened this issue Aug 17, 2024 · 0 comments · Fixed by #2881
Closed

add means to find the socket address for Serve and WithGracefulShutdown #2879

JosephLenton opened this issue Aug 17, 2024 · 0 comments · Fixed by #2881

Comments

@JosephLenton
Copy link
Contributor

JosephLenton commented Aug 17, 2024

  • [*] I have looked for existing issues (including closed) about this

Feature Request

I would like to get the socket address of Serve and WithGracefulShutdown.

Motivation

I am the maintainer of Axum Test, and the initial motivation behind this is to help with testing servers that have been gracefully shutdown. The way Axum Test works is by having a TestServer, and one passes in a Router or a IntoMakeService, and the TestServer then sets that up to be served.

This is relevant, as it means a developer cannot call Serve::with_graceful_shutdown before passing their application into a TestServer.

I can extend my code to allow that. However I need to know what address the Serve is running on, in order to then make requests to it. Ideally I'd like to be able to just get it from Serve directly.

Proposal

I'd propose to add the methods Serve::local_addr and WithGracefulShutdown::local_addr. This is pretty simple to do, and the code would be something like:

#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
impl<M, S> Serve<M, S> {
    pub fn local_addr(&self) -> io::Result<std::net::SocketAddr> {
        self.tcp_listener.local_addr()
    }
}

impl<M, S, F> WithGracefulShutdown<M, S, F> {
    pub fn local_addr(&self) -> io::Result<std::net::SocketAddr> {
        self.tcp_listener.local_addr()
    }
}

I would be happy to make a PR for this myself if there is interest.

Alternatives

Could offer a means to expose the TcpListener.

Another alternative could be to move the with_graceful_shutdown to be attached earlier, before calling serve. This would make it separate to what the service is listening to, and could also solve my issue (although this would be a large and breaking API change).

JosephLenton added a commit to JosephLenton/axum that referenced this issue Aug 18, 2024
Adds methods for exposing the address the Axum servers are bound to.

 * add `Serve::local_addr`
 * add `WithGracefulShutdown::local_addr`

Implements tokio-rs#2879
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant