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 package net
import ( import (
"fmt"
"log" "log"
"net" "net"
"regexp"
"strings"
)
var (
portSuffixRegex = regexp.MustCompile(":\\d{0,5}$")
) )
type Peer struct { type Peer struct {
Address string 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 // Sends the given content to the peer
func (p *Peer) SendToPeer(content []byte) { func (p *Peer) SendToPeer(content []byte) {
// Build up a connection // Build up a connection

View File

@ -63,9 +63,7 @@ func readPeersFile(path string) error {
// Iterate over it, line by line // Iterate over it, line by line
for _, line := range strings.Split(readCont, "\n") { for _, line := range strings.Split(readCont, "\n") {
// Append newly created peer to array // Append newly created peer to array
peers = append(peers, Peer{ peers = append(peers, CreatePeer(line))
Address: line,
})
} }
return nil return nil
@ -75,9 +73,7 @@ func readPeersFile(path string) error {
func readPeersString(raw string) { func readPeersString(raw string) {
for _, peer := range strings.Split(raw, ",") { for _, peer := range strings.Split(raw, ",") {
// Append newly created peer to array // Append newly created peer to array
peers = append(peers, Peer{ peers = append(peers, CreatePeer(peer))
Address: strings.TrimSpace(peer),
})
} }
} }