From 890bf92e90043aec5712819733729896c9cb2c80 Mon Sep 17 00:00:00 2001 From: mikkelam Date: Sun, 4 Aug 2024 17:04:40 +0200 Subject: [PATCH] Remove usage of slog, add error logging capability --- Makefile | 13 ++++----- fast/fast-api.go | 29 +++++++++++--------- main.go | 69 ++++++++++++++++++++++++------------------------ utils/printer.go | 9 +++++++ 4 files changed, 66 insertions(+), 54 deletions(-) diff --git a/Makefile b/Makefile index 9dd7f41..e1e54c7 100644 --- a/Makefile +++ b/Makefile @@ -36,19 +36,16 @@ lint: ## Run golangci-lint @echo "Running golangci-lint" @golangci-lint run +format: ## Run go fmt + @echo "Running go fmt" + @go fmt ./... + .PHONY: build build: ## Compile the project @echo "Building ${OWNER} ${BIN_NAME} ${VERSION}" @echo "GOPATH=${GOPATH}" - ${GOCC} build -ldflags "-X main.version=${VERSION} -X main.commit=${COMMIT} -X main.date=${DATE} -X main.commit=${COMMIT}" -o ${BIN_NAME} - -.PHONY: deps -deps: ## Download project dependencies - ${GOCC} mod tidy + ${GOCC} build -a -ldflags "-w -s -X main.version=${VERSION} -X main.commit=${COMMIT} -X main.date=${DATE} -X main.commit=${COMMIT}" -o ${BIN_NAME} -.PHONY: test -test: ## Run golang tests - ${GOCC} test ./... .PHONY: clean diff --git a/fast/fast-api.go b/fast/fast-api.go index 5098238..eed0971 100644 --- a/fast/fast-api.go +++ b/fast/fast-api.go @@ -2,9 +2,10 @@ package fast import ( "bytes" + "errors" "fmt" "io" - "log/slog" + printer "mikkelam/fast-cli/utils" "net/http" "regexp" ) @@ -13,8 +14,11 @@ import ( var UseHTTPS = true // GetUrls returns a list of urls to the fast api downloads -func GetUrls(urlCount uint64) (urls []string) { - token := getFastToken() +func GetUrls(urlCount uint64) (urls []string, err error) { + token, err := getFastToken() + if err != nil { + return nil, err + } httpProtocol := "https" if !UseHTTPS { @@ -23,17 +27,17 @@ func GetUrls(urlCount uint64) (urls []string) { url := fmt.Sprintf("%s://api.fast.com/netflix/speedtest?https=%t&token=%s&urlCount=%d", httpProtocol, UseHTTPS, token, urlCount) - slog.Debug(fmt.Sprintf("getting download urls from %s", url)) + printer.Debugln(fmt.Sprintf("getting download urls from %s", url)) jsonData, _ := getPage(url) re := regexp.MustCompile("(?U)\"url\":\"(.*)\"") reUrls := re.FindAllStringSubmatch(jsonData, -1) - slog.Debug("urls:") + printer.Debugln("urls:") for _, arr := range reUrls { urls = append(urls, arr[1]) - slog.Debug(fmt.Sprintf(" - %s", arr[1])) + printer.Debugln(fmt.Sprintf(" - %s", arr[1])) } return @@ -49,7 +53,7 @@ func GetDefaultURL() (url string) { return } -func getFastToken() (token string) { +func getFastToken() (token string, err error) { baseURL := "https://fast.com" if !UseHTTPS { baseURL = "http://fast.com" @@ -61,7 +65,7 @@ func getFastToken() (token string) { scriptNames := re.FindAllString(fastBody, 1) scriptURL := fmt.Sprintf("%s/%s", baseURL, scriptNames[0]) - slog.Debug(fmt.Sprintf("trying to get fast api token from %s", scriptURL)) + printer.Debugln(fmt.Sprintf("trying to get fast api token from %s", scriptURL)) // Extract the token scriptBody, _ := getPage(scriptURL) @@ -71,12 +75,13 @@ func getFastToken() (token string) { if len(tokens) > 0 { token = tokens[0][7 : len(tokens[0])-1] - slog.Debug(fmt.Sprintf("found token %s", token)) + printer.Debugln(fmt.Sprintf("found token %s", token)) } else { - slog.Warn("no token found") - } + err := errors.New("could not find fast api token") + printer.Debugln(err) - return + } + return token, err } func getPage(url string) (contents string, err error) { diff --git a/main.go b/main.go index a948f47..c463365 100644 --- a/main.go +++ b/main.go @@ -5,16 +5,13 @@ import ( "encoding/json" "fmt" "io" - "log/slog" - "mikkelam/fast-cli/fast" - "mikkelam/fast-cli/utils" - format "mikkelam/fast-cli/utils" - meters "mikkelam/fast-cli/utils" - printer "mikkelam/fast-cli/utils" "net/http" "os" "time" + "mikkelam/fast-cli/fast" + "mikkelam/fast-cli/utils" + "github.com/urfave/cli/v2" ) @@ -92,41 +89,45 @@ func main() { } if err := app.Run(os.Args); err != nil { - printer.Println(err) + utils.Println(err) os.Exit(1) } } -func initAppconfig() { +func initApputils() { utils.AppConfig.Debug = debugOutput utils.AppConfig.JsonOutput = jsonOutput if debugOutput { - printer.Debugln("Debug logging enabled") + utils.Debugln("Debug logging enabled") } - printer.Debugln("Using HTTPS") + utils.Debugln("Using HTTPS") if notHTTPS { - printer.Debugln("Not using HTTPS") + utils.Debugln("Not using HTTPS") } } func run(c *cli.Context) error { - initAppconfig() + initApputils() fast.UseHTTPS = !notHTTPS - urls := fast.GetUrls(4) + urls, err := fast.GetUrls(4) + if err != nil { + utils.Errorf("Error getting urls from fast.com service: %v\n", err) + return err + } - printer.Debugf("Got %d urls from fast.com service\n", len(urls)) + utils.Debugf("Got %d urls from fast.com service\n", len(urls)) if len(urls) == 0 { - printer.Println("Using fallback endpoint") + utils.Println("Using fallback endpoint") urls = append(urls, fast.GetDefaultURL()) } downloadSpeed, err := measureDownloadSpeed(urls) if err != nil { - printer.Fprintf(os.Stderr, "Error measuring download speed: %v\n", err) + utils.Fprintf(os.Stderr, "Error measuring download speed: %v\n", err) return err } @@ -134,7 +135,7 @@ func run(c *cli.Context) error { if checkUpload { uploadSpeed, err = measureUploadSpeed(urls) if err != nil { - printer.Fprintf(os.Stderr, "Error measuring upload speed: %v\n", err) + utils.Fprintf(os.Stderr, "Error measuring upload speed: %v\n", err) return err } } @@ -171,12 +172,12 @@ func printFinalSpeeds(downloadSpeed *Speed, uploadSpeed *Speed, checkUpload bool func measureDownloadSpeed(urls []string) (Speed, error) { client := &http.Client{} count := uint64(len(urls)) - primaryBandwidthMeter := meters.BandwidthMeter{} + primaryBandwidthMeter := utils.BandwidthMeter{} completed := make(chan bool) primaryBandwidthMeter.Start() if !simpleProgress { - printer.Println("⬇️ Estimating download speed...") + utils.Println("⬇️ Estimating download speed...") } for _, url := range urls { @@ -185,14 +186,14 @@ func measureDownloadSpeed(urls []string) (Speed, error) { request, err := http.NewRequest("GET", url, nil) if err != nil { - slog.Error("Failed to create request", "error", err) + utils.Errorln("Failed to create request", "error", err) return } request.Header.Set("User-Agent", displayVersion) response, err := client.Do(request) if err != nil { - slog.Error("Failed to perform request", "error", err) + utils.Errorln("Failed to perform request", "error", err) return } defer response.Body.Close() @@ -200,7 +201,7 @@ func measureDownloadSpeed(urls []string) (Speed, error) { tapMeter := io.TeeReader(response.Body, &primaryBandwidthMeter) _, err = io.Copy(io.Discard, tapMeter) if err != nil { - slog.Error("Failed to copy response body", "error", err) + utils.Errorln("Failed to copy response body", "error", err) return } }(url) @@ -218,12 +219,12 @@ func measureUploadSpeed(urls []string) (Speed, error) { chunkSize := 1024 * 1024 // 1 MB chunk count := uint64(len(urls)) - primaryBandwidthMeter := meters.BandwidthMeter{} + primaryBandwidthMeter := utils.BandwidthMeter{} completed := make(chan bool) primaryBandwidthMeter.Start() if !simpleProgress { - printer.Println("\n⬆️ Estimating upload speed...") + utils.Println("\n⬆️ Estimating upload speed...") } for _, url := range urls { go func(url string) { @@ -234,7 +235,7 @@ func measureUploadSpeed(urls []string) (Speed, error) { request, err := http.NewRequest("POST", url, tapMeter) if err != nil { - slog.Error("Failed to create request", "error", err) + utils.Errorln("Failed to create request", "error", err) return } request.Header.Set("User-Agent", displayVersion) @@ -246,18 +247,18 @@ func measureUploadSpeed(urls []string) (Speed, error) { buffer := &bytes.Buffer{} _, err = io.Copy(buffer, tapReadMeter) if err != nil { - slog.Error("Failed to copy request body", "error", err) + utils.Errorln("Failed to copy request body", "error", err) return } request.Body = io.NopCloser(buffer) resp, err := client.Do(request) if err != nil { - slog.Error("Failed to perform request", "error", err) + utils.Errorln("Failed to perform request", "error", err) return } resp.Body.Close() if err != nil { - slog.Error("Failed to close response body", "error", err) + utils.Errorln("Failed to close response body", "error", err) return } } @@ -269,7 +270,7 @@ func measureUploadSpeed(urls []string) (Speed, error) { speed, unit := utils.BitsPerSecWithUnit(primaryBandwidthMeter.Bandwidth()) return Speed{Speed: speed, Unit: unit}, nil } -func monitorProgress(bandwidthMeter *meters.BandwidthMeter, bytesToRead uint64, completed chan bool, total uint64) { +func monitorProgress(bandwidthMeter *utils.BandwidthMeter, bytesToRead uint64, completed chan bool, total uint64) { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() @@ -281,7 +282,7 @@ func monitorProgress(bandwidthMeter *meters.BandwidthMeter, bytesToRead uint64, case <-timeout: if !simpleProgress { printProgress(bandwidthMeter, bytesToRead) - // printer.Println("\n🕒 Max duration reached, terminating the test.") + // utils.Println("\n🕒 Max duration reached, terminating the test.") } return @@ -300,16 +301,16 @@ func monitorProgress(bandwidthMeter *meters.BandwidthMeter, bytesToRead uint64, } } -func printProgress(bandwidthMeter *meters.BandwidthMeter, bytesToRead uint64) { +func printProgress(bandwidthMeter *utils.BandwidthMeter, bytesToRead uint64) { if !simpleProgress { // Cycle through spinner states spinner := spinnerStates[spinnerIndex] spinnerIndex = (spinnerIndex + 1) % len(spinnerStates) - printer.Printf("\r%s %s - %s completed", + utils.Printf("\r%s %s - %s completed", spinner, - format.BitsPerSec(bandwidthMeter.Bandwidth()), - format.Percent(bandwidthMeter.BytesRead(), bytesToRead)) + utils.BitsPerSec(bandwidthMeter.Bandwidth()), + utils.Percent(bandwidthMeter.BytesRead(), bytesToRead)) } } diff --git a/utils/printer.go b/utils/printer.go index 9e1ebf6..3fe9afc 100644 --- a/utils/printer.go +++ b/utils/printer.go @@ -3,6 +3,7 @@ package utils import ( "fmt" "io" + "os" ) func PrintJSON(format string, a ...any) { @@ -46,3 +47,11 @@ func Print(a ...any) { fmt.Print(a...) } } + +func Errorln(a ...any) { + fmt.Fprintln(os.Stderr, a...) +} + +func Errorf(format string, a ...any) { + fmt.Fprintf(os.Stderr, format, a...) +}