Skip to content

Commit

Permalink
Implement peer String() method
Browse files Browse the repository at this point in the history
  • Loading branch information
veggiedefender committed Jan 3, 2020
1 parent a822537 commit 09818df
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
4 changes: 1 addition & 3 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"net"
"strconv"
"time"

"github.com/veggiedefender/torrent-client/bitfield"
Expand Down Expand Up @@ -64,8 +63,7 @@ func recvBitfield(conn net.Conn) (bitfield.Bitfield, error) {
// New connects with a peer, completes a handshake, and receives a handshake
// returns an err if any of those fail.
func New(peer peers.Peer, peerID, infoHash [20]byte) (*Client, error) {
hostPort := net.JoinHostPort(peer.IP.String(), strconv.Itoa(int(peer.Port)))
conn, err := net.DialTimeout("tcp", hostPort, 3*time.Second)
conn, err := net.DialTimeout("tcp", peer.String(), 3*time.Second)
if err != nil {
return nil, err
}
Expand Down
5 changes: 5 additions & 0 deletions peers/peers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/binary"
"fmt"
"net"
"strconv"
)

// Peer encodes connection information for a peer
Expand All @@ -28,3 +29,7 @@ func Unmarshal(peersBin []byte) ([]Peer, error) {
}
return peers, nil
}

func (p Peer) String() string {
return net.JoinHostPort(p.IP.String(), strconv.Itoa(int(p.Port)))
}
16 changes: 16 additions & 0 deletions peers/peers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,19 @@ func TestUnmarshal(t *testing.T) {
assert.Equal(t, test.output, peers)
}
}

func TestString(t *testing.T) {
tests := []struct {
input Peer
output string
}{
{
input: Peer{IP: net.IP{127, 0, 0, 1}, Port: 8080},
output: "127.0.0.1:8080",
},
}
for _, test := range tests {
s := test.input.String()
assert.Equal(t, test.output, s)
}
}

0 comments on commit 09818df

Please sign in to comment.