Skip to content

Commit

Permalink
add TryJoinHostPort func
Browse files Browse the repository at this point in the history
  • Loading branch information
dogancanbakir committed Sep 7, 2023
1 parent febf0ad commit 3b1e24d
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
16 changes: 16 additions & 0 deletions net/net.go
Original file line number Diff line number Diff line change
@@ -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
}
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)
}
})
}
}

0 comments on commit 3b1e24d

Please sign in to comment.