Skip to content
This repository was archived by the owner on Dec 14, 2020. It is now read-only.

Commit e8daada

Browse files
alanconwayvcabbage
authored andcommitted
Fix Dial() host:port parsing to handle IPv6 literals.
Fixes #184 Signed-off-by: Alan Conway <aconway@redhat.com>
1 parent 7c41f1a commit e8daada

2 files changed

Lines changed: 42 additions & 6 deletions

File tree

client.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,9 @@ func Dial(addr string, opts ...ConnOption) (*Client, error) {
4444
if err != nil {
4545
return nil, err
4646
}
47-
host, port, err := net.SplitHostPort(u.Host)
48-
if err != nil {
49-
host = u.Host
50-
port = "5672" // use default port values if parse fails
47+
host, port := u.Hostname(), u.Port()
48+
if port == "" {
49+
port = "5672"
5150
if u.Scheme == "amqps" {
5251
port = "5671"
5352
}
@@ -74,11 +73,11 @@ func Dial(addr string, opts ...ConnOption) (*Client, error) {
7473
dialer := &net.Dialer{Timeout: c.connectTimeout}
7574
switch u.Scheme {
7675
case "amqp", "":
77-
c.net, err = dialer.Dial("tcp", host+":"+port)
76+
c.net, err = dialer.Dial("tcp", net.JoinHostPort(host, port))
7877
case "amqps":
7978
c.initTLSConfig()
8079
c.tlsNegotiation = false
81-
c.net, err = tls.DialWithDialer(dialer, "tcp", host+":"+port, c.tlsConfig)
80+
c.net, err = tls.DialWithDialer(dialer, "tcp", net.JoinHostPort(host, port), c.tlsConfig)
8281
default:
8382
return nil, errorErrorf("unsupported scheme %q", u.Scheme)
8483
}

local_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// +build local
2+
3+
package amqp_test
4+
5+
import (
6+
"net"
7+
"testing"
8+
9+
"pack.ag/amqp"
10+
)
11+
12+
// Tests that require a local broker running on the standard AMQP port.
13+
14+
func TestDial_IPV6(t *testing.T) {
15+
if c, err := amqp.Dial("amqp://localhost"); err != nil {
16+
t.Skip("can't connect to local AMQP server")
17+
} else {
18+
c.Close()
19+
}
20+
l, err := net.Listen("tcp6", "[::]:0")
21+
if err != nil {
22+
t.Skip("ipv6 not supported")
23+
}
24+
l.Close()
25+
26+
for _, u := range []string{"amqp://[::]:5672", "amqp://[::]"} {
27+
u := u // Don't use range variable in func literal.
28+
t.Run(u, func(t *testing.T) {
29+
c, err := amqp.Dial(u)
30+
if err != nil {
31+
t.Errorf("%q: %v", u, err)
32+
} else {
33+
c.Close()
34+
}
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)