-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: [#504] Route supports configure timeout #97
Changes from 27 commits
8bd8af2
6e09e22
25ba222
c7f81ea
4963969
c0c1222
d890362
b3a3267
11475d3
94b45f0
4ec125d
02287ab
e920b4a
c07c05d
9a463c5
3e30263
0fa7a3c
53e56ac
f3c2a10
ec3ded3
22e1c33
087bf1b
86f5d3b
18ee0ea
ec70760
c67ff88
051970a
66aa240
7a0668e
b4c16c6
8fd8b39
49bbdd6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package gin | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"time" | ||
|
||
contractshttp "github.com/goravel/framework/contracts/http" | ||
"github.com/goravel/framework/contracts/config" | ||
) | ||
|
||
// TimeoutMiddleware creates middleware to set a timeout for a request | ||
func TimeoutMiddleware(config config.Config) contractshttp.Middleware { | ||
return func(ctx contractshttp.Context) { | ||
timeout := time.Duration(config.GetInt("http.timeout_request", 1)) * time.Second | ||
timeoutCtx, cancel := context.WithTimeout(ctx.Context(), timeout) | ||
defer cancel() | ||
|
||
ctx.WithContext(timeoutCtx) | ||
Check failure on line 19 in timeout_middleware.go GitHub Actions / lint / nilaway
Check failure on line 19 in timeout_middleware.go GitHub Actions / codecov / codecov
Check failure on line 19 in timeout_middleware.go GitHub Actions / test / ubuntu (1.22)
Check failure on line 19 in timeout_middleware.go GitHub Actions / lint / lint
Check failure on line 19 in timeout_middleware.go GitHub Actions / test / ubuntu (1.23)
|
||
|
||
go ctx.Request().Next() | ||
|
||
select { | ||
case <-ctx.Request().Origin().Context().Done(): | ||
if timeoutCtx.Err() == context.DeadlineExceeded { | ||
ctx.Response().Writer().WriteHeader(http.StatusGatewayTimeout) | ||
_, _ = ctx.Response().Writer().Write([]byte("Request timed out")) | ||
hwbrzzl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ctx.Request().AbortWithStatus(http.StatusGatewayTimeout) | ||
} | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add test cases for the new logic in
route_test.go
.