Skip to content

Instantly share code, notes, and snippets.

@starius
Created December 4, 2016 03:07
Show Gist options
  • Save starius/45472174f8bd97989c1eb9bc64d50468 to your computer and use it in GitHub Desktop.
Save starius/45472174f8bd97989c1eb9bc64d50468 to your computer and use it in GitHub Desktop.
package main
import (
"io/ioutil"
"net/http"
"time"
"log"
"fmt"
)
const (
name = "bzip2-1.0.6.tar.gz"
contentType = "application/x-tar"
frame = 100
pause = "5ms"
longPauseAt = 200000
longPause = "35s"
)
func main() {
data, err := ioutil.ReadFile(name)
if err != nil {
log.Fatal("Failed to read file: %s", err)
}
duration, err := time.ParseDuration(pause)
if err != nil {
log.Fatal("Failed to parse pause duration: %s", err)
}
longDuration, err := time.ParseDuration(longPause)
if err != nil {
log.Fatal("Failed to parse long pause duration: %s", err)
}
if longPauseAt >= len(data) {
log.Fatal("longPauseAt >= len(data): %d >= %d", longPauseAt, len(data))
}
http.HandleFunc("/" + name, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data)))
w.Header().Set("Content-Type", contentType)
d := data
totalSent := 0
hasLongPaused := false
for len(d) != 0 {
f := frame
if f > len(d) {
f = len(d)
}
n, err := w.Write(d[:f])
if err != nil || n == 0 {
return
}
totalSent += n
if totalSent >= longPauseAt && !hasLongPaused {
time.Sleep(longDuration)
hasLongPaused = true
} else {
time.Sleep(duration)
}
d = d[n:]
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment