Skip to content

Commit

Permalink
Optimize IsFromLocal()
Browse files Browse the repository at this point in the history
  • Loading branch information
gaby committed Sep 23, 2024
1 parent fbc24e8 commit 7b13bfe
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 15 deletions.
14 changes: 1 addition & 13 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 0 additions & 2 deletions ctx_interface_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 58 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
}

0 comments on commit 7b13bfe

Please sign in to comment.