Hit cloudflare's endpoint to up and download bytes and report rate
authorJacob Casper <dev@jacobcasper.com>
Thu, 20 Jun 2024 00:56:40 +0000 (19:56 -0500)
committerJacob Casper <dev@jacobcasper.com>
Thu, 20 Jun 2024 00:56:40 +0000 (19:56 -0500)
go.mod [new file with mode: 0644]
main.go [new file with mode: 0644]

diff --git a/go.mod b/go.mod
new file mode 100644 (file)
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 (file)
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())
+}