io.go 989 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package proxy
  2. import (
  3. "context"
  4. "golang.org/x/time/rate"
  5. "io"
  6. "time"
  7. )
  8. const burstLimit = 1000 * 1000 * 1000
  9. type Reader struct {
  10. r io.Reader
  11. limiter *rate.Limiter
  12. ctx context.Context
  13. }
  14. type Writer struct {
  15. w io.Writer
  16. limiter *rate.Limiter
  17. ctx context.Context
  18. }
  19. // NewReader returns a reader that implements io.Reader with rate limiting.
  20. func NewReader(r io.Reader) *Reader {
  21. return &Reader{
  22. r: r,
  23. ctx: context.Background(),
  24. }
  25. }
  26. // SetRateLimit sets rate limit (bytes/sec) to the reader.
  27. func (s *Reader) SetRateLimit(bytesPerSec float64) {
  28. s.limiter = rate.NewLimiter(rate.Limit(bytesPerSec), burstLimit)
  29. s.limiter.AllowN(time.Now(), burstLimit) // spend initial burst
  30. }
  31. // Read reads bytes into p.
  32. func (s *Reader) Read(p []byte) (int, error) {
  33. if s.limiter == nil {
  34. return s.r.Read(p)
  35. }
  36. n, err := s.r.Read(p)
  37. if err != nil {
  38. return n, err
  39. }
  40. if err := s.limiter.WaitN(s.ctx, n); err != nil {
  41. return n, err
  42. }
  43. return n, nil
  44. }