Last active
December 17, 2015 13:10
-
-
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).
This file contains hidden or 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 ( | |
"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