Skip to content

Commit

Permalink
MGO-134 Add helper method to return a readable server address. (globa…
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaneHarvey authored and craiggwilson committed May 25, 2017
1 parent 1826d82 commit 39b4000
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,17 @@ func (s *Session) LiveServers() (addrs []string) {
return addrs
}

// ReadableServer returns a server address which is suitable for reading
// according to the current session.
func (s *Session) ReadableServer() (string, error) {
socket, err := s.acquireSocket(true)
if err != nil {
return "", err
}
defer socket.Release()
return socket.server.Addr, nil
}

// DB returns a value representing the named database. If name
// is empty, the database name provided in the dialed URL is
// used instead. If that is also empty, "test" is used as a
Expand Down
20 changes: 20 additions & 0 deletions session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,26 @@ func (s *S) TestURLInvalidReadPreferenceTags(c *C) {
}
}

func (s *S) TestReadableServer(c *C) {
session, err := mgo.Dial("localhost:40011,localhost:40012,localhost:40013")
c.Assert(err, IsNil)
defer session.Close()

session.SetMode(mgo.Primary, true)
primary_address, err := session.ReadableServer()
c.Assert(err, IsNil)
c.Assert(primary_address, Equals, "localhost:40011")

session.SetMode(mgo.Secondary, true)
secondary_address, err := session.ReadableServer()
c.Assert(err, IsNil)

valid_addresses := []string{"localhost:40012", "localhost:40013"}
if secondary_address != valid_addresses[0] && secondary_address != valid_addresses[1] {
c.Fatalf("secondary_address should be in %v, not: %v", valid_addresses, secondary_address)
}
}

func (s *S) TestInsertFindOne(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
Expand Down

0 comments on commit 39b4000

Please sign in to comment.