timeout_writer.go 891 B

12345678910111213141516171819202122232425262728293031323334
  1. package util
  2. import (
  3. "errors"
  4. "io"
  5. "time"
  6. )
  7. // ErrWriteTimeout is returned when a write timed out
  8. var ErrWriteTimeout = errors.New("write operation failed due to timeout since creation")
  9. // TimeoutWriter wraps an io.Writer that will time out after the given timeout
  10. type TimeoutWriter struct {
  11. writer io.Writer
  12. timeout time.Duration
  13. start time.Time
  14. }
  15. // NewTimeoutWriter creates a new TimeoutWriter
  16. func NewTimeoutWriter(w io.Writer, timeout time.Duration) *TimeoutWriter {
  17. return &TimeoutWriter{
  18. writer: w,
  19. timeout: timeout,
  20. start: time.Now(),
  21. }
  22. }
  23. // Write implements the io.Writer interface, failing if called after the timeout period from creation.
  24. func (tw *TimeoutWriter) Write(p []byte) (n int, err error) {
  25. if time.Since(tw.start) > tw.timeout {
  26. return 0, errors.New("write operation failed due to timeout since creation")
  27. }
  28. return tw.writer.Write(p)
  29. }