Timeout is a middleware that cancels ctx after a given timeout and return a 504 Gateway Timeout error to the client. It's required that you select the ctx.Done() channel to check for the signal if the context has reached its deadline and return, otherwise the timeout signal will be just ignored. i
(timeout time.Duration)
| 30 | // w.Write([]byte("done")) |
| 31 | // }) |
| 32 | func Timeout(timeout time.Duration) func(next http.Handler) http.Handler { |
| 33 | return func(next http.Handler) http.Handler { |
| 34 | fn := func(w http.ResponseWriter, r *http.Request) { |
| 35 | ctx, cancel := context.WithTimeout(r.Context(), timeout) |
| 36 | defer func() { |
| 37 | cancel() |
| 38 | if ctx.Err() == context.DeadlineExceeded { |
| 39 | w.WriteHeader(http.StatusGatewayTimeout) |
| 40 | } |
| 41 | }() |
| 42 | |
| 43 | r = r.WithContext(ctx) |
| 44 | next.ServeHTTP(w, r) |
| 45 | } |
| 46 | return http.HandlerFunc(fn) |
| 47 | } |
| 48 | } |
no test coverage detected