File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -109,6 +109,22 @@ func (c *Client) Disconnect(ctx context.Context) error {
109
109
return c .topology .Disconnect (ctx )
110
110
}
111
111
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
+
112
128
// StartSession starts a new session.
113
129
func (c * Client ) StartSession (opts ... sessionopt.Session ) (* Session , error ) {
114
130
if c .topology .SessionPool == nil {
Original file line number Diff line number Diff line change @@ -406,3 +406,31 @@ func TestClient_CausalConsistency(t *testing.T) {
406
406
require .True (t , sess .Consistent )
407
407
sess .EndSession (ctx )
408
408
}
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
+ }
You can’t perform that action at this time.
0 commit comments