Skip to content

Commit

Permalink
refactor(timeout): add more test cases and handle zero duration case
Browse files Browse the repository at this point in the history
  • Loading branch information
ReneWerner87 committed Jan 7, 2025
1 parent 649488d commit 1077ab4
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions middleware/timeout/timeout.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,26 @@ func New(h fiber.Handler, timeout time.Duration, tErrs ...error) fiber.Handler {
timeoutContext, cancel := context.WithTimeout(ctx.Context(), timeout)
defer cancel()

// Attach the timeout-bound context to the current Fiber context.
// Replace the default Fiber context with our timeout-bound context.
ctx.SetContext(timeoutContext)

// Execute the wrapped handler synchronously.
err := h(ctx)
// Run the handler and check for relevant errors.
err := runHandler(ctx, h, tErrs)

// If the context has timed out, return a request timeout error.
if timeoutContext.Err() != nil && errors.Is(timeoutContext.Err(), context.DeadlineExceeded) {
// If the context actually timed out, return a timeout error.
if errors.Is(timeoutContext.Err(), context.DeadlineExceeded) {
return fiber.ErrRequestTimeout
}

// If the handler returned an error, check whether it's a deadline exceeded
// error or any other listed timeout-triggering error.
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || isCustomError(err, tErrs) {
return fiber.ErrRequestTimeout
}
}
return err
}
}

// runHandler executes the handler and returns fiber.ErrRequestTimeout if it
// sees a deadline exceeded error or one of the custom "timeout-like" errors.
func runHandler(c fiber.Ctx, h fiber.Handler, tErrs []error) error {
// Execute the wrapped handler synchronously.
err := h(c)
// If the context has timed out, return a request timeout error.
if err != nil && (errors.Is(err, context.DeadlineExceeded) || isCustomError(err, tErrs)) {
return fiber.ErrRequestTimeout
}
Expand Down

0 comments on commit 1077ab4

Please sign in to comment.