Skip to content

Commit

Permalink
refactor(internal.fast): make upload speed optional, extract output func
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed May 6, 2021
1 parent b81b9b4 commit 83290fc
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions internal/fast/fast.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type Fast struct {

// Measure does the main job.
// It returns *Fast and error
func Measure() (*Fast, error) {
func Measure(noUp bool) (*Fast, error) {
ctx, cancel := chromedp.NewContext(
context.Background(),
chromedp.WithLogf(log.Printf),
Expand All @@ -32,43 +32,60 @@ func Measure() (*Fast, error) {
defer cancel()

fast := new(Fast)
err := chromedp.Run(ctx,
cmds := []chromedp.Action{
emulation.SetUserAgentOverride(`chromedp/chromedp v0.6.10`),
chromedp.Navigate(`https://fast.com`),
chromedp.ScrollIntoView(`footer`),
chromedp.WaitVisible(`#speed-value.succeeded`),
chromedp.Text(`#speed-value.succeeded`, &fast.Down, chromedp.NodeVisible, chromedp.ByQuery),
chromedp.Text(`#speed-units.succeeded`, &fast.DownUnit, chromedp.NodeVisible, chromedp.ByQuery),
chromedp.Click(`#show-more-details-link`),
chromedp.WaitVisible(`#upload-value.succeeded`),
chromedp.Text(`#upload-value.succeeded`, &fast.Up, chromedp.NodeVisible, chromedp.ByQuery),
chromedp.Text(`#upload-units.succeeded`, &fast.UpUnit, chromedp.NodeVisible, chromedp.ByQuery),
)
}

if !noUp {
cmds = append(cmds, chromedp.Click(`#show-more-details-link`),
chromedp.WaitVisible(`#upload-value.succeeded`),
chromedp.Text(`#upload-value.succeeded`, &fast.Up, chromedp.NodeVisible, chromedp.ByQuery),
chromedp.Text(`#upload-units.succeeded`, &fast.UpUnit, chromedp.NodeVisible, chromedp.ByQuery),
)
}

err := chromedp.Run(ctx, cmds...)

return fast, err
}

// Run is the ready to use API.
// For customization call Measure().
func Run() {
func Run(noUp bool) {
start := time.Now()

fast, err := Measure()
fast, err := Measure(noUp)
if err != nil {
log.Fatal(err)
}

Out(fast, start)
}

func Out(fast *Fast, start time.Time) {
hasUp := fast.Up != "" && fast.UpUnit != ""

// No color for windows
if os.PathSeparator == '\\' {
fmt.Printf("download speed: %s %s\n", fast.Down, fast.DownUnit)
fmt.Printf("upload speed: %s %s\n", fast.Up, fast.UpUnit)
if hasUp {
fmt.Printf("upload speed: %s %s\n", fast.Up, fast.UpUnit)
}
fmt.Printf("\n")
fmt.Printf("> took: %f secs\n", time.Since(start).Seconds())

return
}

fmt.Printf("\033[36mdownload speed:\033[m \033[32m%s\033[m %s\n", fast.Down, fast.DownUnit)
fmt.Printf("\033[36mupload speed:\033[m \033[31m%s\033[m %s\n", fast.Up, fast.UpUnit)
if hasUp {
fmt.Printf("\033[36mupload speed:\033[m \033[31m%s\033[m %s\n", fast.Up, fast.UpUnit)
}
fmt.Printf("\n")
fmt.Printf("\033[36m> took: \033[33m%f\033[m secs\n", time.Since(start).Seconds())
}

0 comments on commit 83290fc

Please sign in to comment.