Skip to content

Instantly share code, notes, and snippets.

@ewalk153
Last active December 17, 2015 13:10
Show Gist options
  • Save ewalk153/5615581 to your computer and use it in GitHub Desktop.
Save ewalk153/5615581 to your computer and use it in GitHub Desktop.
Go script for testing your internet connection (by downloading an large file and verifying that it continues to download).
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
const BLOCK_SIZE = 4096
const MAX_PAUSE = 30 * time.Second
func monitor(body io.Reader, c chan int) {
bytes := make([]byte, BLOCK_SIZE)
for {
if _, err := body.Read(bytes); err != nil {
c <- 0
break
} else {
c <- 1
}
}
}
func delay(tick time.Time) time.Duration {
return time.Now().Sub(tick)
}
func TrackDownload(url string) {
var c = make(chan int)
tick := time.Now()
count := 0
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
go monitor(resp.Body, c)
go func() {
for {
time.Sleep(1 * 1e9)
c <- 2
}
}()
for {
switch <-c {
case 0:
fmt.Printf("Completed with: %v blocks.\n", count)
return
case 1:
tick = time.Now()
count += 1
case 2:
delay := delay(tick)
fmt.Printf("Count: %v (last packet received %v ago).\n", count, delay)
if delay > MAX_PAUSE {
fmt.Printf("Declared dead; no update after %v.\n", delay)
return
}
}
}
}
func GetUrl() string {
if len(os.Args) < 2 {
fmt.Printf("Used to track when a connection drops for HTTP downloads\n\n")
fmt.Printf("Usage:\n\t%v URL\n", os.Args[0])
fmt.Printf("Example:\n\t%v \"http://releases.ubuntu.com//precise/ubuntu-12.04.2-desktop-amd64.iso\"\n", os.Args[0])
os.Exit(1)
}
return os.Args[1]
}
func main() {
TrackDownload(GetUrl())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment