timeout.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. func Timeout(timeout time.Duration) func(next http.Handler) http.Handler {
  31. return func(next http.Handler) http.Handler {
  32. fn := func(w http.ResponseWriter, r *http.Request) {
  33. ctx, cancel := context.WithTimeout(r.Context(), timeout)
  34. defer func() {
  35. cancel()
  36. if ctx.Err() == context.DeadlineExceeded {
  37. w.WriteHeader(http.StatusGatewayTimeout)
  38. }
  39. }()
  40. r = r.WithContext(ctx)
  41. next.ServeHTTP(w, r)
  42. }
  43. return http.HandlerFunc(fn)
  44. }
  45. }