Skip to content

Commit 185c5f1

Browse files
committed
nat: PortBinding: implement stringer
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent 6bb1d15 commit 185c5f1

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

nat/nat.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ type PortBinding struct {
1717
HostPort string
1818
}
1919

20+
func (pb *PortBinding) String() string {
21+
if pb.HostPort == "" {
22+
return ""
23+
}
24+
if pb.HostIP == "" {
25+
return pb.HostPort
26+
}
27+
return net.JoinHostPort(pb.HostIP, pb.HostPort)
28+
}
29+
2030
// PortMap is a collection of PortBinding indexed by Port
2131
type PortMap map[Port][]PortBinding
2232

nat/nat_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,68 @@ func TestStringer(t *testing.T) {
842842
}
843843
}
844844

845+
func TestPortBinding(t *testing.T) {
846+
tests := []struct {
847+
doc string
848+
binding *PortBinding
849+
expect string
850+
}{
851+
{
852+
doc: "no host mapping",
853+
binding: &PortBinding{},
854+
expect: "",
855+
},
856+
{
857+
doc: "ipv4 missing port",
858+
binding: &PortBinding{
859+
HostIP: "192.168.1.100",
860+
},
861+
expect: "",
862+
},
863+
{
864+
doc: "ipv4",
865+
binding: &PortBinding{
866+
HostIP: "192.168.1.100",
867+
HostPort: "6000",
868+
},
869+
expect: "192.168.1.100:6000",
870+
},
871+
{
872+
doc: "ipv6 missing port",
873+
binding: &PortBinding{
874+
HostIP: "::1",
875+
},
876+
expect: "",
877+
},
878+
{
879+
doc: "ipv6",
880+
binding: &PortBinding{
881+
HostIP: "::1",
882+
HostPort: "6000",
883+
},
884+
expect: "[::1]:6000",
885+
},
886+
// FIXME(thaJeztah): this should be invalid
887+
{
888+
doc: "ipv6 with braces",
889+
binding: &PortBinding{
890+
HostIP: "[::1]",
891+
HostPort: "6000",
892+
},
893+
expect: "[[::1]]:6000",
894+
},
895+
}
896+
897+
for _, tc := range tests {
898+
t.Run(tc.doc, func(t *testing.T) {
899+
actual := tc.binding.String()
900+
if actual != tc.expect {
901+
t.Errorf("Expected %s got %s", tc.expect, actual)
902+
}
903+
})
904+
}
905+
}
906+
845907
func BenchmarkParsePortSpecs(b *testing.B) {
846908
specs := [][]string{
847909
{"1234/tcp", "2345/udp", "3456/sctp"},

0 commit comments

Comments
 (0)