Skip to content

Commit 58677d5

Browse files
authored
feat: Add Drop method to DefaultCtx for silent connection termination (#3257)
* Add Drop method to DefaultCtx and remove redundant checks Introduced a Drop method in DefaultCtx for closing connections, enabling easier resource management. Removed unnecessary nil-checks for headers in manager_msgp to simplify code logic. Added a unit test to ensure the new Drop method behaves as expected. * Add `Drop` method to Fiber context API documentation The `Drop` method allows silently terminating client connections without sending HTTP headers or a response body. This is useful for scenarios like mitigating DDoS attacks or blocking unauthorized access to sensitive endpoints. Example usage and function signature are included in the updated documentation. * Remove extraneous blank line in documentation. Eliminated an unnecessary blank line in the API context documentation for improved readability and formatting consistency. No functional changes were made to the content. * Update API documentation example to return "Hello World!" Revised the example code in the API documentation to return a generic "Hello World!" string instead of a dynamic response. This improves consistency and simplifies the example for easier understanding. * Refactor Drop method and extend test coverage. Simplified the Drop method by inlining the connection close call. Added new test cases to ensure proper handling of no-response scenarios and improved overall test coverage. * fix golangci-lint issue * Add test for Ctx.Drop with middleware interaction This test ensures the correct behavior of the Ctx.Drop method when used with middleware, including response handling and error scenarios. It verifies that the middleware and handler properly handle the Drop call and its resulting effects. * Add Drop method to DefaultCtx for closing connections The Drop method allows closing connections without sending a response, improving control over connection handling. Also updated a test assertion to use StatusOK for improved readability and consistency. * Refine Drop method comments to clarify error handling. Explain the rationale for not wrapping errors in the Drop method. Emphasize that the returned error is solely for logging and not for further propagation or processing. * Update Drop method documentation for clarity Clarified the `Drop` method's behavior, specifying that it closes the connection without sending headers or a body. Added examples of use cases, such as DDoS mitigation and blocking sensitive endpoints. * Refactor response header setting in middleware. Replaced the direct header setting with the `Set` method for consistency and improved clarity. Removed a test case checking for a panic on closed response body as it is no longer applicable.
1 parent 1c9b6ce commit 58677d5

File tree

5 files changed

+83
-6
lines changed

5 files changed

+83
-6
lines changed

ctx.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1978,3 +1978,11 @@ func (c *DefaultCtx) setMatched(matched bool) {
19781978
func (c *DefaultCtx) setRoute(route *Route) {
19791979
c.route = route
19801980
}
1981+
1982+
// Drop closes the underlying connection without sending any response headers or body.
1983+
// This can be useful for silently terminating client connections, such as in DDoS mitigation
1984+
// or when blocking access to sensitive endpoints.
1985+
func (c *DefaultCtx) Drop() error {
1986+
//nolint:wrapcheck // error wrapping is avoided to keep the operation lightweight and focused on connection closure.
1987+
return c.RequestCtx().Conn().Close()
1988+
}

ctx_interface_gen.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

ctx_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5847,6 +5847,59 @@ func Test_GenericParseTypeBoolean(t *testing.T) {
58475847
}
58485848
}
58495849

5850+
// go test -run Test_Ctx_Drop -v
5851+
func Test_Ctx_Drop(t *testing.T) {
5852+
t.Parallel()
5853+
5854+
app := New()
5855+
5856+
// Handler that calls Drop
5857+
app.Get("/block-me", func(c Ctx) error {
5858+
return c.Drop()
5859+
})
5860+
5861+
// Additional handler that just calls return
5862+
app.Get("/no-response", func(_ Ctx) error {
5863+
return nil
5864+
})
5865+
5866+
// Test the Drop method
5867+
resp, err := app.Test(httptest.NewRequest(MethodGet, "/block-me", nil))
5868+
require.Error(t, err)
5869+
require.Nil(t, resp)
5870+
5871+
// Test the no-response handler
5872+
resp, err = app.Test(httptest.NewRequest(MethodGet, "/no-response", nil))
5873+
require.NoError(t, err)
5874+
require.NotNil(t, resp)
5875+
require.Equal(t, StatusOK, resp.StatusCode)
5876+
require.Equal(t, "0", resp.Header.Get("Content-Length"))
5877+
}
5878+
5879+
// go test -run Test_Ctx_DropWithMiddleware -v
5880+
func Test_Ctx_DropWithMiddleware(t *testing.T) {
5881+
t.Parallel()
5882+
5883+
app := New()
5884+
5885+
// Middleware that calls Drop
5886+
app.Use(func(c Ctx) error {
5887+
err := c.Next()
5888+
c.Set("X-Test", "test")
5889+
return err
5890+
})
5891+
5892+
// Handler that calls Drop
5893+
app.Get("/block-me", func(c Ctx) error {
5894+
return c.Drop()
5895+
})
5896+
5897+
// Test the Drop method
5898+
resp, err := app.Test(httptest.NewRequest(MethodGet, "/block-me", nil))
5899+
require.Error(t, err)
5900+
require.Nil(t, resp)
5901+
}
5902+
58505903
// go test -run Test_GenericParseTypeString
58515904
func Test_GenericParseTypeString(t *testing.T) {
58525905
t.Parallel()

docs/api/ctx.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,27 @@ app.Get("/", func(c fiber.Ctx) error {
463463
})
464464
```
465465

466+
## Drop
467+
468+
Terminates the client connection silently without sending any HTTP headers or response body.
469+
470+
This can be used for scenarios where you want to block certain requests without notifying the client, such as mitigating
471+
DDoS attacks or protecting sensitive endpoints from unauthorized access.
472+
473+
```go title="Signature"
474+
func (c fiber.Ctx) Drop() error
475+
```
476+
477+
```go title="Example"
478+
app.Get("/", func(c fiber.Ctx) error {
479+
if c.IP() == "192.168.1.1" {
480+
return c.Drop()
481+
}
482+
483+
return c.SendString("Hello World!")
484+
})
485+
```
486+
466487
## Format
467488

468489
Performs content-negotiation on the [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) HTTP header. It uses [Accepts](ctx.md#accepts) to select a proper format from the supplied offers. A default handler can be provided by setting the `MediaType` to `"default"`. If no offers match and no default is provided, a 406 (Not Acceptable) response is sent. The Content-Type is automatically set when a handler is selected.

middleware/cache/manager_msgp.go

Lines changed: 0 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)