From dadb811838cf79f5aaf374f726ff04719edd46aa Mon Sep 17 00:00:00 2001 From: maride Date: Sat, 20 Jun 2020 19:07:58 +0200 Subject: [PATCH] Add port number if not already present --- net/peer.go | 25 +++++++++++++++++++++++++ net/sender.go | 8 ++------ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/net/peer.go b/net/peer.go index 7c12c8c..d4ef47b 100644 --- a/net/peer.go +++ b/net/peer.go @@ -1,14 +1,39 @@ package net import ( + "fmt" "log" "net" + "regexp" + "strings" +) + +var ( + portSuffixRegex = regexp.MustCompile(":\\d{0,5}$") ) type Peer struct { Address string } +// Creates a peer from the given address +func CreatePeer(address string) Peer { + // Clean line + address = strings.TrimSpace(address) + + // Check if a port is already part of the address + // This is the lazy way: if a IPv6 literal is given without square brackets and without a port, this will fail badly. + if !portSuffixRegex.MatchString(address) { + // Port number is not yet part of the address, so append the default port number + address = fmt.Sprintf("%s:%d", address, ServerPort) + } + + // Return constructed Peer + return Peer{ + Address: address, + } +} + // Sends the given content to the peer func (p *Peer) SendToPeer(content []byte) { // Build up a connection diff --git a/net/sender.go b/net/sender.go index 818517f..a6b7b76 100644 --- a/net/sender.go +++ b/net/sender.go @@ -63,9 +63,7 @@ func readPeersFile(path string) error { // Iterate over it, line by line for _, line := range strings.Split(readCont, "\n") { // Append newly created peer to array - peers = append(peers, Peer{ - Address: line, - }) + peers = append(peers, CreatePeer(line)) } return nil @@ -75,9 +73,7 @@ func readPeersFile(path string) error { func readPeersString(raw string) { for _, peer := range strings.Split(raw, ",") { // Append newly created peer to array - peers = append(peers, Peer{ - Address: strings.TrimSpace(peer), - }) + peers = append(peers, CreatePeer(peer)) } }