Skip to content

Commit

Permalink
Handle IPv6 in isMovedError
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddzxy committed Apr 26, 2024
1 parent 90c7a41 commit 920f148
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
3 changes: 3 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package redis
import (
"context"
"errors"
"github.com/redis/go-redis/v9/internal"
"io"
"net"
"strings"
Expand Down Expand Up @@ -129,7 +130,9 @@ func isMovedError(err error) (moved bool, ask bool, addr string) {
if ind == -1 {
return false, false, ""
}

addr = s[ind+1:]
addr = internal.GetAddr(addr)
return
}

Expand Down
20 changes: 20 additions & 0 deletions internal/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package internal

import (
"context"
"net"
"strings"
"time"

Expand Down Expand Up @@ -64,3 +65,22 @@ func ReplaceSpaces(s string) string {

return builder.String()
}

func GetAddr(addr string) string {
ind := strings.LastIndex(addr, ":")
if ind == -1 {
return ""
}

port := addr[ind+1:]
host := addr[:ind]
if string(host[0]) == "[" && string(host[len(host)-1]) == "]" {
host = host[1 : len(host)-1]
}

if net.ParseIP(host) == nil {
return ""
}

return net.JoinHostPort(host, port)
}
21 changes: 21 additions & 0 deletions internal/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,24 @@ func TestIsLower(t *testing.T) {
Expect(isLower(str)).To(BeTrue())
})
}

func TestGetAddr(t *testing.T) {
It("getAddr", func() {
str := "127.0.0.1:1234"
Expect(GetAddr(str)).To(Equal(str))

str = "[::1]:1234"
Expect(GetAddr(str)).To(Equal(str))

str = "[fd01:abcd::7d03]:6379"
Expect(GetAddr(str)).To(Equal(str))

Expect(GetAddr("::1:1234")).To(Equal("[::1]:1234"))

Expect(GetAddr("fd01:abcd::7d03:6379")).To(Equal("[fd01:abcd::7d03]:6379"))

Expect(GetAddr("127.0.0.1")).To(Equal(""))

Expect(GetAddr("127")).To(Equal(""))
})
}

0 comments on commit 920f148

Please sign in to comment.