diff options
-rw-r--r-- | client/client.go | 21 | ||||
-rw-r--r-- | client/client_test.go | 2 | ||||
-rw-r--r-- | gobgp/cmd/common.go | 2 |
3 files changed, 21 insertions, 4 deletions
diff --git a/client/client.go b/client/client.go index b85360c2..7fa9d0ec 100644 --- a/client/client.go +++ b/client/client.go @@ -39,14 +39,23 @@ func defaultGRPCOptions() []grpc.DialOption { return []grpc.DialOption{grpc.WithTimeout(time.Second), grpc.WithBlock(), grpc.WithInsecure()} } -func NewGoBGPClient(target string, opts ...grpc.DialOption) (*GoBGPClient, error) { +// New returns a new GoBGPClient using the given target and options for dialing +// to the grpc server. If an error occurs during dialing it will be returned and +// GoBGPClient will be nil. +func New(target string, opts ...grpc.DialOption) (*GoBGPClient, error) { + return NewWith(context.Background(), target, opts...) +} + +// NewWith is like New, but uses the given ctx to cancel or expire the current +// attempt to connect if it becomes Done before the connection succeeds. +func NewWith(ctx context.Context, target string, opts ...grpc.DialOption) (*GoBGPClient, error) { if target == "" { target = ":50051" } if len(opts) == 0 { opts = defaultGRPCOptions() } - conn, err := grpc.Dial(target, opts...) + conn, err := grpc.DialContext(ctx, target, opts...) if err != nil { return nil, err } @@ -54,6 +63,14 @@ func NewGoBGPClient(target string, opts ...grpc.DialOption) (*GoBGPClient, error return &GoBGPClient{conn: conn, cli: cli}, nil } +// NewFrom returns a new GoBGPClient, using the given conn and cli for the +// underlying connection. The given grpc.ClientConn connection is expected to be +// initialized and paired with the api client. See New to have the connection +// dialed for you. +func NewFrom(conn *grpc.ClientConn, cli api.GobgpApiClient) *GoBGPClient { + return &GoBGPClient{conn: conn, cli: cli} +} + func (cli *GoBGPClient) Close() error { return cli.conn.Close() } diff --git a/client/client_test.go b/client/client_test.go index 9825f91b..3f07a6ad 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -30,7 +30,7 @@ func TestGetNeighbor(test *testing.T) { go s.Serve() g := api.NewGrpcServer(s, ":50051") go g.Serve() - cli, err := NewGoBGPClient("") + cli, err := New("") err = cli.StartServer(&config.Global{ Config: config.GlobalConfig{ As: 1, diff --git a/gobgp/cmd/common.go b/gobgp/cmd/common.go index 7d2f77aa..db229c11 100644 --- a/gobgp/cmd/common.go +++ b/gobgp/cmd/common.go @@ -223,7 +223,7 @@ func (v vrfs) Less(i, j int) bool { func newClient() *cli.GoBGPClient { target := net.JoinHostPort(globalOpts.Host, strconv.Itoa(globalOpts.Port)) - client, err := cli.NewGoBGPClient(target) + client, err := cli.New(target) if err != nil { exitWithError(err) } |