-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware_timeout.go
45 lines (37 loc) · 1.17 KB
/
middleware_timeout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package fiber
import (
"context"
"errors"
"net/http"
"time"
contractshttp "github.com/goravel/framework/contracts/http"
)
// Timeout creates middleware to set a timeout for a request.
// NOTICE: It does not cancel long running executions. Underlying executions must handle timeout by using context.Context parameter.
// For details, see https://github.com/valyala/fasthttp/issues/965
func Timeout(timeout time.Duration) contractshttp.Middleware {
return func(ctx contractshttp.Context) {
timeoutCtx, cancel := context.WithTimeout(ctx.Context(), timeout)
defer cancel()
ctx.WithContext(timeoutCtx)
done := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
LogFacade.Request(ctx.Request()).Error(r)
// TODO can be customized in https://github.com/goravel/goravel/issues/521
_ = ctx.Response().Status(http.StatusInternalServerError).String("Internal Server Error").Render()
}
close(done)
}()
ctx.Request().Next()
}()
select {
case <-done:
case <-ctx.Context().Done():
if errors.Is(ctx.Context().Err(), context.DeadlineExceeded) {
ctx.Request().AbortWithStatus(http.StatusGatewayTimeout)
}
}
}
}