Created
September 13, 2023 16:26
-
-
Save dmage/b4d3c6e733c4a9a42a4830eddf1df9da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"net/http" | |
"time" | |
) | |
type SlowDevNull struct { | |
interval time.Duration | |
maxBitsPerInterval int64 | |
n int64 | |
t time.Time | |
} | |
func NewSlowDevNull(bitsPerSecond int64, interval time.Duration) *SlowDevNull { | |
return &SlowDevNull{ | |
interval: interval, | |
maxBitsPerInterval: bitsPerSecond * int64(interval) / int64(time.Second), | |
} | |
} | |
func (s *SlowDevNull) Write(p []byte) (n int, err error) { | |
now := time.Now() | |
if s.t.IsZero() { | |
s.t = now | |
} | |
nextInterval := s.t.Add(s.interval) | |
if now.After(nextInterval) { | |
s.n = 0 | |
s.t = now | |
} | |
s.n += int64(len(p)) * 8 | |
for s.n > s.maxBitsPerInterval { | |
s.n -= s.maxBitsPerInterval | |
time.Sleep(time.Until(nextInterval)) | |
s.t = nextInterval | |
nextInterval = s.t.Add(s.interval) | |
} | |
return len(p), nil | |
} | |
func main() { | |
const Mbps = 1000 * 1000 | |
slowDevNull := NewSlowDevNull(5*Mbps, 10*time.Millisecond) | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
io.Copy(slowDevNull, r.Body) | |
http.Error(w, "OK", http.StatusOK) | |
}) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment