refactor(context): replace hardcoded localhost IPs with constants (#4481)

This commit is contained in:
Paulo Henrique 2025-12-27 08:25:17 -03:00 committed by GitHub
parent 26c3a62865
commit 915e4c90d2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 9 additions and 3 deletions

View File

@ -1910,7 +1910,7 @@ func TestContextClientIP(t *testing.T) {
resetContextForClientIPTests(c) resetContextForClientIPTests(c)
// IPv6 support // IPv6 support
c.Request.RemoteAddr = "[::1]:12345" c.Request.RemoteAddr = fmt.Sprintf("[%s]:12345", localhostIPv6)
assert.Equal(t, "20.20.20.20", c.ClientIP()) assert.Equal(t, "20.20.20.20", c.ClientIP())
resetContextForClientIPTests(c) resetContextForClientIPTests(c)
@ -3212,7 +3212,7 @@ func TestContextCopyShouldNotCancel(t *testing.T) {
}() }()
addr := strings.Split(l.Addr().String(), ":") 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 { if err != nil {
t.Error(fmt.Errorf("request error: %w", err)) t.Error(fmt.Errorf("request error: %w", err))
return return

View File

@ -83,7 +83,7 @@ func TestLoadHTMLGlobDebugMode(t *testing.T) {
} }
func TestH2c(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 { if err != nil {
t.Error(err) t.Error(err)
} }

View File

@ -19,6 +19,12 @@ import (
// BindKey indicates a default bind key. // BindKey indicates a default bind key.
const BindKey = "_gin-gonic/gin/bindkey" 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. // Bind is a helper function for given interface object and returns a Gin middleware.
func Bind(val any) HandlerFunc { func Bind(val any) HandlerFunc {
value := reflect.ValueOf(val) value := reflect.ValueOf(val)