package main
import (
+ "bufio"
"bytes"
"fmt"
"io"
+ "log"
"net/http"
+ "net/url"
"strconv"
"time"
)
var UPLOAD_PATH = "https://speed.cloudflare.com/__up"
var DOWNLOAD_PATH = "https://speed.cloudflare.com/__down"
+var iter = 2
func main() {
- var measurementBytes int64 = 50 * MiB
+ var measurementBytes int64 = 10 * MiB
+ dUrl, _ := url.Parse(DOWNLOAD_PATH + "?bytes=" + strconv.FormatInt(measurementBytes, 10))
+ uUrl, _ := url.Parse(UPLOAD_PATH)
+ down := &http.Request{
+ Method: "GET",
+ URL: dUrl,
+ }
+
+ 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)))
+ up := &http.Request{
+ Method: "POST",
+ URL: uUrl,
+ Header: headers,
+ ContentLength: measurementBytes,
+ Body: r,
+ }
+
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)
+ for i := 0; i < iter; i++ {
+ rate := measureRequest(client, down, measurementBytes)
+ fmt.Printf("Down: KiB/s %v\n", rate/KiB)
+ }
+ for i := 0; i < iter; i++ {
+ rate := measureRequest(client, up, measurementBytes)
+ fmt.Printf("Up: KiB/s %v\n", rate/KiB)
+ }
}
-// Returns the rate in bytes / ms
-func downloadTest(client *http.Client, b int64) int64 {
+// Returns the rate in bytes / s
+func measureRequest(client *http.Client, r *http.Request, b int64) float64 {
var start = time.Now()
- resp, _ := client.Get(DOWNLOAD_PATH + "?bytes=" + strconv.FormatInt(b, 10))
+ resp, err := client.Do(r)
+ if err != nil {
+ fmt.Printf("%v\n", r.Body)
+ log.Fatal(err)
+ }
defer resp.Body.Close()
- _, _ = io.ReadAll(resp.Body)
- return (b / time.Since(start).Milliseconds())
+ _, _ = io.ReadAll(bufio.NewReaderSize(resp.Body, int(b)))
+ return bytePerSecond(b, time.Since(start))
}
-// 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())
+func bytePerSecond(size int64, d time.Duration) float64 {
+ return float64(size) / d.Seconds()
}