Add port number if not already present

This commit is contained in:
maride 2020-06-20 19:07:58 +02:00
parent d986b6714c
commit dadb811838
2 changed files with 27 additions and 6 deletions

View File

@ -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

View File

@ -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))
}
}