Skip to content

Commit 0fe202c

Browse files
committed
Add WithDeadlineFunc/WithTimeout middlewares
1 parent 986df46 commit 0fe202c

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

middleware.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,20 @@ func WithMetrics(app string) MiddlewareFunc {
248248
}
249249
}
250250
}
251+
252+
// WithTimeout returns a MiddlewareFunc that wraps a Func with a context timeout.
253+
func WithTimeout(timeout time.Duration) MiddlewareFunc {
254+
return WithDeadlineFunc(func(ctx context.Context) time.Time { return time.Now().Add(timeout) })
255+
}
256+
257+
// WithDeadlineFunc returns a MiddlewareFunc that wraps a Func with a context deadline.
258+
// The deadline is determined by calling the provided function df.
259+
func WithDeadlineFunc(df func(context.Context) time.Time) MiddlewareFunc {
260+
return func(next Func) Func {
261+
return func(ctx context.Context) error {
262+
ctx, cancel := context.WithDeadline(ctx, df(ctx))
263+
defer cancel()
264+
return next(ctx)
265+
}
266+
}
267+
}

0 commit comments

Comments
 (0)