Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add TryJoinHostPort func #255

Merged
merged 2 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions net/net.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package netutil

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) {
if host == "" {
return "", &net.AddrError{Err: "missing host", Addr: host}
}

if port == "" {
return host, ErrMissingPort
}

return net.JoinHostPort(host, port), nil
}
57 changes: 57 additions & 0 deletions net/net_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}