From 4de8189f71a240eb0b1104029ad0abf316777d16 Mon Sep 17 00:00:00 2001 From: Jacob Casper Date: Thu, 27 Jun 2024 20:07:20 -0500 Subject: [PATCH] Create type alias for Bytes and convenience methods --- main.go | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index 3a799ad..0487062 100644 --- a/main.go +++ b/main.go @@ -12,21 +12,43 @@ import ( "time" ) +type Byte int + const ( - B = 1 - KiB = 1 << (10 * iota) + B Byte = 1 + KiB Byte = 1 << (10 * iota) MiB GiB TiB ) -var UPLOAD_PATH = "https://speed.cloudflare.com/__up" -var DOWNLOAD_PATH = "https://speed.cloudflare.com/__down" -var iter = 2 +func (b Byte) String() string { + if b == B { + return "B" + } + if b == KiB { + return "KiB" + } + if b == MiB { + return "MiB" + } + if b == GiB { + return "GiB" + } + if b == TiB { + return "TiB" + } + return "B" +} + +const UPLOAD_PATH = "https://speed.cloudflare.com/__up" +const DOWNLOAD_PATH = "https://speed.cloudflare.com/__down" + +var iter = 10 func main() { - var measurementBytes int64 = 10 * MiB - dUrl, _ := url.Parse(DOWNLOAD_PATH + "?bytes=" + strconv.FormatInt(measurementBytes, 10)) + bytes := 10 * MiB + dUrl, _ := url.Parse(DOWNLOAD_PATH + "?bytes=" + strconv.FormatInt(int64(bytes), 10)) uUrl, _ := url.Parse(UPLOAD_PATH) down := &http.Request{ Method: "GET", @@ -45,21 +67,21 @@ func main() { } // Can't figure out how to reset r on each request so unfortunately just reinstantiate :/ -func getUp(url *url.URL, measurementBytes int64) *http.Request { +func getUp(url *url.URL, measurement Byte) *http.Request { var headers http.Header = make(map[string][]string) headers.Add("Content-Type", "text/plain;charset=UTF-8") - r := io.NopCloser(bytes.NewReader(make([]byte, measurementBytes))) + r := io.NopCloser(bytes.NewReader(make([]byte, measurement))) return &http.Request{ Method: "POST", URL: url, Header: headers, - ContentLength: measurementBytes, + ContentLength: int64(measurement), Body: r, } } // Returns the rate in bytes / s -func measureRequest(client *http.Client, r *http.Request, b int64) float64 { +func measureRequest(client *http.Client, r *http.Request, b Byte) float64 { var start = time.Now() resp, err := client.Do(r) if err != nil { @@ -73,6 +95,6 @@ func measureRequest(client *http.Client, r *http.Request, b int64) float64 { return bytePerSecond(b, time.Since(start)) } -func bytePerSecond(size int64, d time.Duration) float64 { +func bytePerSecond(size Byte, d time.Duration) float64 { return float64(size) / d.Seconds() } -- 2.20.1