From: Jacob Casper Date: Fri, 28 Jun 2024 01:07:20 +0000 (-0500) Subject: Create type alias for Bytes and convenience methods X-Git-Url: https://git.jacobcasper.com/?a=commitdiff_plain;h=4de8189f71a240eb0b1104029ad0abf316777d16;p=speedtest.git Create type alias for Bytes and convenience methods --- 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() }