Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

Commit

Permalink
proxy: add LocalAddr() method
Browse files Browse the repository at this point in the history
This method exposes the underlying listener's local address. It will be
useful to get the address if the listener binds to an address in the
form "127.0.0.1:0", which picks up a random port.

/xref planetscale/surfaces#111
  • Loading branch information
fatih committed Mar 2, 2021
1 parent 1ed032f commit fce701a
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions proxy/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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://")
Expand Down

0 comments on commit fce701a

Please sign in to comment.