From 915e4c90d28ec4cffc6eb146e208ab5a65eac772 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Sat, 27 Dec 2025 08:25:17 -0300 Subject: [PATCH] refactor(context): replace hardcoded localhost IPs with constants (#4481) --- context_test.go | 4 ++-- gin_test.go | 2 +- utils.go | 6 ++++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/context_test.go b/context_test.go index 126646fc..016fa86d 100644 --- a/context_test.go +++ b/context_test.go @@ -1910,7 +1910,7 @@ func TestContextClientIP(t *testing.T) { resetContextForClientIPTests(c) // IPv6 support - c.Request.RemoteAddr = "[::1]:12345" + c.Request.RemoteAddr = fmt.Sprintf("[%s]:12345", localhostIPv6) assert.Equal(t, "20.20.20.20", c.ClientIP()) resetContextForClientIPTests(c) @@ -3212,7 +3212,7 @@ func TestContextCopyShouldNotCancel(t *testing.T) { }() addr := strings.Split(l.Addr().String(), ":") - res, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/", addr[len(addr)-1])) + res, err := http.Get(fmt.Sprintf("http://%s:%s/", localhostIP, addr[len(addr)-1])) if err != nil { t.Error(fmt.Errorf("request error: %w", err)) return diff --git a/gin_test.go b/gin_test.go index 81343d88..43c9494d 100644 --- a/gin_test.go +++ b/gin_test.go @@ -83,7 +83,7 @@ func TestLoadHTMLGlobDebugMode(t *testing.T) { } func TestH2c(t *testing.T) { - ln, err := net.Listen("tcp", "127.0.0.1:0") + ln, err := net.Listen("tcp", localhostIP+":0") if err != nil { t.Error(err) } diff --git a/utils.go b/utils.go index 971e9433..62517784 100644 --- a/utils.go +++ b/utils.go @@ -19,6 +19,12 @@ import ( // BindKey indicates a default bind key. const BindKey = "_gin-gonic/gin/bindkey" +// localhostIP indicates the default localhost IP address. +const localhostIP = "127.0.0.1" + +// localhostIPv6 indicates the default localhost IPv6 address. +const localhostIPv6 = "::1" + // Bind is a helper function for given interface object and returns a Gin middleware. func Bind(val any) HandlerFunc { value := reflect.ValueOf(val)