main.go 1.05 KB
package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"time"
)

func main() {
	var host string
	var out io.Writer

	if l := len(os.Args); l == 1 {
		b, err := ioutil.ReadFile("host.iperf")
		if err != nil {
			host = "172.30.0.1"
		} else {
			host = string(b)
		}
		out = os.Stdout
	} else if l == 2 {
		host = os.Args[1]
		out = os.Stdout
	} else {
		f, err := os.OpenFile(os.Args[2], os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()

		host = os.Args[1]
		out = f
	}

	test("hw-ethernet", host, out)
}

func test(code, host string, out io.Writer) {
	c := exec.Command("iperf", "-c", host, "-i", "1", "-t", "10")
	stdout, err := c.StdoutPipe()

	err = c.Start()
	if err != nil {
		log.Fatal(err)
	}

	state := 0

	s := bufio.NewScanner(stdout)
	for s.Scan() {
		fmt.Fprintf(out, "{\"%v\": {\"progress\": %v, \"result\": \"%v\"}}\n", code, state, s.Text())
		if state < 90 {
			state += 10
		}
	}

	time.Sleep(1)

	fmt.Fprintf(out, "{\"%v\": {\"progress\": 100, \"result\": \"\"}}\n", code)
}