From dbfe353e9392651619e2f1841e32ab881811d092 Mon Sep 17 00:00:00 2001 From: Jacob Casper Date: Wed, 19 Jun 2024 19:56:40 -0500 Subject: [PATCH] Hit cloudflare's endpoint to up and download bytes and report rate --- go.mod | 3 +++ main.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5797d85 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module jacobcasper.com/speedtest + +go 1.22.4 diff --git a/main.go b/main.go new file mode 100644 index 0000000..fa7de78 --- /dev/null +++ b/main.go @@ -0,0 +1,49 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strconv" + "time" +) + +const ( + B = 1 + KiB = 1 << (10 * iota) + MiB + GiB + TiB +) + +var UPLOAD_PATH = "https://speed.cloudflare.com/__up" +var DOWNLOAD_PATH = "https://speed.cloudflare.com/__down" + +func main() { + var measurementBytes int64 = 50 * MiB + client := &http.Client{} + rate := downloadTest(client, measurementBytes) + fmt.Printf("B/ms %v\n", rate) + r := bytes.NewReader(make([]byte, measurementBytes)) + rate = uploadTest(client, r) + fmt.Printf("B/ms %v\n", rate) +} + +// Returns the rate in bytes / ms +func downloadTest(client *http.Client, b int64) int64 { + var start = time.Now() + resp, _ := client.Get(DOWNLOAD_PATH + "?bytes=" + strconv.FormatInt(b, 10)) + defer resp.Body.Close() + _, _ = io.ReadAll(resp.Body) + return (b / time.Since(start).Milliseconds()) +} + +// Returns the rate in bytes / ms +func uploadTest(client *http.Client, r *bytes.Reader) int64 { + var start = time.Now() + resp, _ := client.Post(UPLOAD_PATH, "text/plain;charset=UTF-8", r) + defer resp.Body.Close() + _, _ = io.ReadAll(resp.Body) + return (r.Size() / time.Since(start).Milliseconds()) +} -- 2.20.1