v3: Optimize IsFromLocal() performance (#3140)

Optimize IsFromLocal()
pull/3142/head
Juan Calderon-Perez 2024-09-23 09:16:52 -04:00 committed by GitHub
parent fbc24e83d6
commit f8c514cb25
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 59 additions and 15 deletions

14
ctx.go
View File

@ -1841,21 +1841,9 @@ func (c *DefaultCtx) IsProxyTrusted() bool {
return false
}
var localHosts = [...]string{"127.0.0.1", "::1"}
// IsLocalHost will return true if address is a localhost address.
func (*DefaultCtx) isLocalHost(address string) bool {
for _, h := range localHosts {
if address == h {
return true
}
}
return false
}
// IsFromLocal will return true if request came from local.
func (c *DefaultCtx) IsFromLocal() bool {
return c.isLocalHost(c.fasthttp.RemoteIP().String())
return c.fasthttp.RemoteIP().IsLoopback()
}
// Bind You can bind body, cookie, headers etc. into the map, map slice, struct easily by using Binding method.

View File

@ -318,8 +318,6 @@ type Ctx interface {
// If EnableTrustedProxyCheck false, it returns true
// IsProxyTrusted can check remote ip by proxy ranges and ip map.
IsProxyTrusted() bool
// IsLocalHost will return true if address is a localhost address.
isLocalHost(address string) bool
// IsFromLocal will return true if request came from local.
IsFromLocal() bool
// Bind You can bind body, cookie, headers etc. into the map, map slice, struct easily by using Binding method.

View File

@ -6352,3 +6352,61 @@ func Benchmark_Ctx_IsProxyTrusted(b *testing.B) {
})
})
}
func Benchmark_Ctx_IsFromLocalhost(b *testing.B) {
// Scenario without localhost check
b.Run("Non_Localhost", func(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://google.com:8080/test")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
// Scenario without localhost check in parallel
b.Run("Non_Localhost_Parallel", func(b *testing.B) {
app := New()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://google.com:8080/test")
for pb.Next() {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
})
// Scenario with localhost check
b.Run("Localhost", func(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://localhost:8080/test")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
// Scenario with localhost check in parallel
b.Run("Localhost_Parallel", func(b *testing.B) {
app := New()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://localhost:8080/test")
for pb.Next() {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
})
}