-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #12 from KlassnayaAfrodita/patch-1
Create timeoutMiddleware.go
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package middleware | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"time" | ||
) | ||
|
||
type TimeoutMiddleware struct { | ||
Timeout time.Duration | ||
} | ||
|
||
// NewTimeoutMiddleware creates a new instance of timeout middleware | ||
func NewTimeoutMiddleware(timeout time.Duration) *TimeoutMiddleware { | ||
return &TimeoutMiddleware{Timeout: timeout} | ||
} | ||
|
||
// Handle adds a timeout to the request context | ||
func (tm *TimeoutMiddleware) Handle(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
|
||
ctx, cancel := context.WithTimeout(r.Context(), tm.Timeout) | ||
defer cancel() | ||
|
||
// Replace the request context with a new context with a timeout | ||
r = r.WithContext(ctx) | ||
|
||
done := make(chan struct{}) | ||
go func() { | ||
next.ServeHTTP(w, r) | ||
close(done) | ||
}() | ||
|
||
// End the request when the timeout is reached or after the main handler completes | ||
select { | ||
case <-done: | ||
// The handler completed its work before the timeout | ||
case <-ctx.Done(): | ||
// Timeout: cancel the request and return 504 status | ||
http.Error(w, http.StatusText(http.StatusGatewayTimeout), http.StatusGatewayTimeout) | ||
} | ||
}) | ||
} |