Bladeren bron

Fix #173 (on garyburd/redigo).

The IANA spec for the redis: prefix allows an empty db specifier
(path consisting just of '/') and says to use db 0 in that case.
Daniel Brotsky 9 jaren geleden
bovenliggende
commit
bcc277df96
2 gewijzigde bestanden met toevoegingen van 27 en 13 verwijderingen
  1. 7 4
      redis/conn.go
  2. 20 9
      redis/conn_test.go

+ 7 - 4
redis/conn.go

@@ -162,7 +162,7 @@ func Dial(network, address string, options ...DialOption) (Conn, error) {
 	return c, nil
 }
 
-var pathDBRegexp = regexp.MustCompile(`/(\d+)\z`)
+var pathDBRegexp = regexp.MustCompile(`/(\d*)\z`)
 
 // DialURL connects to a Redis server at the given URL using the Redis
 // URI scheme. URLs should follow the draft IANA specification for the
@@ -199,9 +199,12 @@ func DialURL(rawurl string, options ...DialOption) (Conn, error) {
 
 	match := pathDBRegexp.FindStringSubmatch(u.Path)
 	if len(match) == 2 {
-		db, err := strconv.Atoi(match[1])
-		if err != nil {
-			return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
+		db := 0
+		if len(match[1]) > 0 {
+			db, err = strconv.Atoi(match[1])
+			if err != nil {
+				return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
+			}
 		}
 		if db != 0 {
 			options = append(options, DialDatabase(db))

+ 20 - 9
redis/conn_test.go

@@ -516,15 +516,26 @@ func TestDialURLPassword(t *testing.T) {
 }
 
 func TestDialURLDatabase(t *testing.T) {
-	var buf bytes.Buffer
-	_, err := redis.DialURL("redis://localhost/3", dialTestConn(strings.NewReader("+OK\r\n"), &buf))
-	if err != nil {
-		t.Error("dial error:", err)
-	}
-	expected := "*2\r\n$6\r\nSELECT\r\n$1\r\n3\r\n"
-	actual := buf.String()
-	if actual != expected {
-		t.Errorf("commands = %q, want %q", actual, expected)
+	var buf3 bytes.Buffer
+	_, err3 := redis.DialURL("redis://localhost/3", dialTestConn(strings.NewReader("+OK\r\n"), &buf3))
+	if err3 != nil {
+		t.Error("dial error:", err3)
+	}
+	expected3 := "*2\r\n$6\r\nSELECT\r\n$1\r\n3\r\n"
+	actual3 := buf3.String()
+	if actual3 != expected3 {
+		t.Errorf("commands = %q, want %q", actual3, expected3)
+	}
+	// empty DB means 0
+	var buf0 bytes.Buffer
+	_, err0 := redis.DialURL("redis://localhost/", dialTestConn(strings.NewReader("+OK\r\n"), &buf0))
+	if err0 != nil {
+		t.Error("dial error:", err0)
+	}
+	expected0 := ""
+	actual0 := buf0.String()
+	if actual0 != expected0 {
+		t.Errorf("commands = %q, want %q", actual0, expected0)
 	}
 }