Skip to content

Commit b61d6fd

Browse files
committed
GODRIVER-372 Add Ping method to mongo.Client
1 parent 3e1dd84 commit b61d6fd

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

mongo/client.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,22 @@ func (c *Client) Disconnect(ctx context.Context) error {
109109
return c.topology.Disconnect(ctx)
110110
}
111111

112+
// Ping verifies that the client can connect to the topology.
113+
// If readPreference is nil then will use the client's default read
114+
// preference.
115+
func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error {
116+
if ctx == nil {
117+
ctx = context.Background()
118+
}
119+
120+
if rp == nil {
121+
rp = c.readPreference
122+
}
123+
124+
_, err := c.topology.SelectServer(ctx, description.ReadPrefSelector(rp))
125+
return err
126+
}
127+
112128
// StartSession starts a new session.
113129
func (c *Client) StartSession(opts ...sessionopt.Session) (*Session, error) {
114130
if c.topology.SessionPool == nil {

mongo/client_internal_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,3 +406,31 @@ func TestClient_CausalConsistency(t *testing.T) {
406406
require.True(t, sess.Consistent)
407407
sess.EndSession(ctx)
408408
}
409+
410+
func TestClient_Ping_DefaultReadPreference(t *testing.T) {
411+
cs := testutil.ConnString(t)
412+
c, err := NewClient(cs.String())
413+
require.NoError(t, err)
414+
require.NotNil(t, c)
415+
416+
err = c.Connect(ctx)
417+
require.NoError(t, err)
418+
419+
err = c.Ping(ctx, nil)
420+
require.NoError(t, err)
421+
}
422+
423+
func TestClient_Ping_InvalidHost(t *testing.T) {
424+
dur, err := time.ParseDuration("1ms")
425+
require.NoError(t, err)
426+
427+
c, err := NewClientWithOptions("mongodb://nohost:27017", clientopt.ServerSelectionTimeout(dur))
428+
require.NoError(t, err)
429+
require.NotNil(t, c)
430+
431+
err = c.Connect(ctx)
432+
require.NoError(t, err)
433+
434+
err = c.Ping(ctx, nil)
435+
require.NotNil(t, err)
436+
}

0 commit comments

Comments
 (0)