error) (int, error) { if n == 0 || err != nil { return n, err } elapsed := time.Since(l.startedAt) l.bytes += int64(n) rate := float64(l.bytes) / elapsed.Seconds() if rate < l.bytesPerSec { return n, nil } d := time.Duration(float64(l.bytes)/l.bytesPerSec*float64(time.Second) - float64(elapsed)) time.Sleep(d) // reset shaping window l.startedAt = time.Now() l.bytes = 0 return n, nil }