Skip to content

Commit

Permalink
fix: handle timeout after ServeHttp has completed
Browse files Browse the repository at this point in the history
  • Loading branch information
kangmingtay committed May 17, 2024
1 parent fcf5941 commit 17d5dab
Showing 1 changed file with 2 additions and 9 deletions.
11 changes: 2 additions & 9 deletions internal/api/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,37 +320,30 @@ func timeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()

timeoutWriter := &timeoutResponseWriter{
w: w,
ctx: ctx,
}

go func() {
<-ctx.Done()

defer func() {
cancel()
err := ctx.Err()

if err == context.DeadlineExceeded {
timeoutWriter.mu.Lock()
defer timeoutWriter.mu.Unlock()
if timeoutWriter.wrote == 0 {
// writer wasn't written to, so we're sending the error payload

httpError := &HTTPError{
HTTPStatus: http.StatusGatewayTimeout,
ErrorCode: ErrorCodeRequestTimeout,
Message: "Processing this request timed out, please retry after a moment.",
}

httpError = httpError.WithInternalError(err)

HandleResponseError(httpError, w, r)
}
}
}()

next.ServeHTTP(timeoutWriter, r.WithContext(ctx))
})
}
Expand Down

0 comments on commit 17d5dab

Please sign in to comment.