Skip to content

Commit

Permalink
Use net.{Join,Split}HostPort for proper ipv6 handling
Browse files Browse the repository at this point in the history
  • Loading branch information
tamird committed Feb 7, 2016
1 parent ac6673f commit 05333d3
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion conn.go
Expand Up @@ -362,7 +362,7 @@ func network(o values) (string, string) {
return "unix", sockPath
}

return "tcp", host + ":" + o.Get("port")
return "tcp", net.JoinHostPort(host, o.Get("port"))
}

type values map[string]string
Expand Down
8 changes: 4 additions & 4 deletions url.go
Expand Up @@ -2,6 +2,7 @@ package pq

import (
"fmt"
"net"
nurl "net/url"
"sort"
"strings"
Expand Down Expand Up @@ -54,12 +55,11 @@ func ParseURL(url string) (string, error) {
accrue("password", v)
}

i := strings.Index(u.Host, ":")
if i < 0 {
if host, port, err := net.SplitHostPort(u.Host); err != nil {
accrue("host", u.Host)
} else {
accrue("host", u.Host[:i])
accrue("port", u.Host[i+1:])
accrue("host", host)
accrue("port", port)
}

if u.Path != "" {
Expand Down
12 changes: 12 additions & 0 deletions url_test.go
Expand Up @@ -16,6 +16,18 @@ func TestSimpleParseURL(t *testing.T) {
}
}

func TestIPv6LoopbackParseURL(t *testing.T) {
expected := "host=::1 port=1234"
str, err := ParseURL("postgres://[::1]:1234")
if err != nil {
t.Fatal(err)
}

if str != expected {
t.Fatalf("unexpected result from ParseURL:\n+ %v\n- %v", str, expected)
}
}

func TestFullParseURL(t *testing.T) {
expected := `dbname=database host=hostname.remote password=top\ secret port=1234 user=username`
str, err := ParseURL("postgres://username:top%20secret@hostname.remote:1234/database")
Expand Down

0 comments on commit 05333d3

Please sign in to comment.