github.com/karrick/gorill@v1.10.3/slow.go (about) 1 package gorill 2 3 import ( 4 "io" 5 "time" 6 ) 7 8 // SlowReader returns a structure that wraps an io.Reader, but sleeps prior to writing data to the 9 // underlying io.Reader. 10 // 11 // bb := gorill.NopCloseBuffer() 12 // sr := gorill.SlowReader(bb, 10*time.Second) 13 // 14 // buf := make([]byte, 1000) 15 // n, err := sr.Read(buf) // this call takes at least 10 seconds to return 16 // // n == 7, err == nil 17 func SlowReader(r io.Reader, d time.Duration) io.Reader { 18 return &slowReader{Reader: r, duration: d} 19 } 20 21 func (s *slowReader) Read(data []byte) (int, error) { 22 time.Sleep(s.duration) 23 return s.Reader.Read(data) 24 } 25 26 type slowReader struct { 27 io.Reader 28 duration time.Duration 29 } 30 31 // SlowWriter returns a structure that wraps an io.Writer, but sleeps prior to writing data to the 32 // underlying io.Writer. 33 // 34 // bb := gorill.NopCloseBuffer() 35 // sw := gorill.SlowWriter(bb, 10*time.Second) 36 // 37 // n, err := sw.Write([]byte("example")) // this call takes at least 10 seconds to return 38 // // n == 7, err == nil 39 func SlowWriter(w io.Writer, d time.Duration) io.Writer { 40 return &slowWriter{Writer: w, duration: d} 41 } 42 43 func (s *slowWriter) Write(data []byte) (int, error) { 44 time.Sleep(s.duration) 45 return s.Writer.Write(data) 46 } 47 48 type slowWriter struct { 49 io.Writer 50 duration time.Duration 51 }