1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2024-11-24 08:12:38 +02:00
imgproxy/router/timer.go

47 lines
1.0 KiB
Go
Raw Normal View History

2021-04-26 13:52:50 +02:00
package router
import (
"context"
"fmt"
"net/http"
"time"
2022-01-13 20:18:48 +02:00
"github.com/imgproxy/imgproxy/v3/config"
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/ierrors"
2021-04-26 13:52:50 +02:00
)
type timerSinceCtxKey = struct{}
2022-01-13 20:18:48 +02:00
func startRequestTimer(r *http.Request) (*http.Request, context.CancelFunc) {
ctx := r.Context()
ctx = context.WithValue(ctx, timerSinceCtxKey{}, time.Now())
ctx, cancel := context.WithTimeout(ctx, time.Duration(config.WriteTimeout)*time.Second)
return r.WithContext(ctx), cancel
2021-04-26 13:52:50 +02:00
}
func ctxTime(ctx context.Context) time.Duration {
if t, ok := ctx.Value(timerSinceCtxKey{}).(time.Time); ok {
return time.Since(t)
}
return 0
}
2022-07-20 11:49:05 +02:00
func CheckTimeout(ctx context.Context) error {
2021-04-26 13:52:50 +02:00
select {
case <-ctx.Done():
d := ctxTime(ctx)
2022-07-19 14:10:18 +02:00
err := ctx.Err()
switch err {
case context.Canceled:
2022-07-20 11:49:05 +02:00
return ierrors.New(499, fmt.Sprintf("Request was cancelled after %v", d), "Cancelled")
2022-07-19 14:10:18 +02:00
case context.DeadlineExceeded:
2022-07-20 11:49:05 +02:00
return ierrors.New(http.StatusServiceUnavailable, fmt.Sprintf("Request was timed out after %v", d), "Timeout")
2022-07-19 14:10:18 +02:00
default:
2022-07-20 11:49:05 +02:00
return err
2021-04-26 13:52:50 +02:00
}
default:
2022-07-20 11:49:05 +02:00
return nil
2021-04-26 13:52:50 +02:00
}
}