From 3b1e24d2133fcc437880eaebc77bb92a6599f235 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Thu, 7 Sep 2023 08:34:29 +0000 Subject: [PATCH 1/2] add TryJoinHostPort func --- net/net.go | 16 ++++++++++++++ net/net_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 net/net.go create mode 100644 net/net_test.go diff --git a/net/net.go b/net/net.go new file mode 100644 index 0000000..a3c4eeb --- /dev/null +++ b/net/net.go @@ -0,0 +1,16 @@ +package netutil + +import "net" + +// TryJoinHostPort joins host and port. If port is empty, it returns host and an error. +func TryJoinHostPort(host, port string) (string, error) { + if host == "" { + return "", &net.AddrError{Err: "missing host", Addr: host} + } + + if port == "" { + return host, &net.AddrError{Err: "missing port", Addr: host} + } + + return net.JoinHostPort(host, port), nil +} diff --git a/net/net_test.go b/net/net_test.go new file mode 100644 index 0000000..377f0c7 --- /dev/null +++ b/net/net_test.go @@ -0,0 +1,57 @@ +package netutil + +import ( + "testing" +) + +func TestTryJoinHostPort(t *testing.T) { + tests := []struct { + name string + host string + port string + want string + wantErr bool + }{ + { + name: "both host and port provided", + host: "localhost", + port: "8080", + want: "localhost:8080", + wantErr: false, + }, + { + name: "empty host", + host: "", + port: "8080", + want: "", + wantErr: true, + }, + { + name: "empty port", + host: "localhost", + port: "", + want: "localhost", + wantErr: true, + }, + { + name: "both host and port empty", + host: "", + port: "", + want: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := TryJoinHostPort(tt.host, tt.port) + if (err != nil) != tt.wantErr { + t.Errorf("TryJoinHostPort() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("TryJoinHostPort() = %v, want %v", got, tt.want) + } + }) + } +} From 48138972b9bf8e13fed39acd6acec5163ae68edc Mon Sep 17 00:00:00 2001 From: mzack Date: Mon, 11 Sep 2023 09:38:33 +0200 Subject: [PATCH 2/2] using custom error --- net/net.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/net/net.go b/net/net.go index a3c4eeb..a3ec78b 100644 --- a/net/net.go +++ b/net/net.go @@ -1,6 +1,11 @@ package netutil -import "net" +import ( + "errors" + "net" +) + +var ErrMissingPort = errors.New("missing port") // TryJoinHostPort joins host and port. If port is empty, it returns host and an error. func TryJoinHostPort(host, port string) (string, error) { @@ -9,7 +14,7 @@ func TryJoinHostPort(host, port string) (string, error) { } if port == "" { - return host, &net.AddrError{Err: "missing port", Addr: host} + return host, ErrMissingPort } return net.JoinHostPort(host, port), nil