You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timeout.go 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package middleware
  2. import (
  3. "context"
  4. "net/http"
  5. "time"
  6. )
  7. // Timeout is a middleware that cancels ctx after a given timeout and return
  8. // a 504 Gateway Timeout error to the client.
  9. //
  10. // It's required that you select the ctx.Done() channel to check for the signal
  11. // if the context has reached its deadline and return, otherwise the timeout
  12. // signal will be just ignored.
  13. //
  14. // ie. a route/handler may look like:
  15. //
  16. // r.Get("/long", func(w http.ResponseWriter, r *http.Request) {
  17. // ctx := r.Context()
  18. // processTime := time.Duration(rand.Intn(4)+1) * time.Second
  19. //
  20. // select {
  21. // case <-ctx.Done():
  22. // return
  23. //
  24. // case <-time.After(processTime):
  25. // // The above channel simulates some hard work.
  26. // }
  27. //
  28. // w.Write([]byte("done"))
  29. // })
  30. //
  31. func Timeout(timeout time.Duration) func(next http.Handler) http.Handler {
  32. return func(next http.Handler) http.Handler {
  33. fn := func(w http.ResponseWriter, r *http.Request) {
  34. ctx, cancel := context.WithTimeout(r.Context(), timeout)
  35. defer func() {
  36. cancel()
  37. if ctx.Err() == context.DeadlineExceeded {
  38. w.WriteHeader(http.StatusGatewayTimeout)
  39. }
  40. }()
  41. r = r.WithContext(ctx)
  42. next.ServeHTTP(w, r)
  43. }
  44. return http.HandlerFunc(fn)
  45. }
  46. }