diff --git a/proxy/client.go b/proxy/client.go index 70f9081..5a90538 100644 --- a/proxy/client.go +++ b/proxy/client.go @@ -4,6 +4,7 @@ import ( "context" "crypto/tls" "crypto/x509" + "errors" "fmt" "io" "net" @@ -52,6 +53,10 @@ type Client struct { // configCache contains the TLS certificate chache for each indiviual // database configCache *tlsCache + + listener net.Listener + // done is closed after a successfull net.Listen bind. + done chan struct{} } // Options are the options for creating a new Client. @@ -89,6 +94,7 @@ func NewClient(opts Options) (*Client, error) { remoteAddr: opts.RemoteAddr, instance: opts.Instance, configCache: newtlsCache(), + done: make(chan struct{}, 0), } if opts.Logger != nil { @@ -129,9 +135,24 @@ func (c *Client) Run(ctx context.Context) error { } defer c.log.Sync() // nolint: errcheck + c.listener = l + close(c.done) + return c.run(ctx, l) } +// LocalAddr returns the address of the local listener. This is by default +// blocking and will only return if the proxy is invoked with the Run() method. +func (c *Client) LocalAddr() (net.Addr, error) { + <-c.done + + if c.listener == nil { + return nil, errors.New("listener is not set") + + } + return c.listener.Addr(), nil +} + func (c *Client) getListener() (net.Listener, error) { if strings.HasPrefix(c.localAddr, "unix://") { p := strings.TrimPrefix(c.localAddr, "unix://")