Skip to content

Commit

Permalink
Remove usage of slog, add error logging capability
Browse files Browse the repository at this point in the history
  • Loading branch information
mikkelam committed Aug 4, 2024
1 parent 3d3108b commit 890bf92
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 54 deletions.
13 changes: 5 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 17 additions & 12 deletions fast/fast-api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package fast

import (
"bytes"
"errors"
"fmt"
"io"
"log/slog"
printer "mikkelam/fast-cli/utils"
"net/http"
"regexp"
)
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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"
Expand All @@ -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)
Expand All @@ -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) {
Expand Down
69 changes: 35 additions & 34 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -92,49 +89,53 @@ 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
}

var uploadSpeed Speed
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
}
}
Expand Down Expand Up @@ -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 {
Expand All @@ -185,22 +186,22 @@ 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()

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)
Expand All @@ -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) {
Expand All @@ -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)
Expand All @@ -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
}
}
Expand All @@ -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()

Expand All @@ -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

Expand All @@ -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))
}
}

Expand Down
9 changes: 9 additions & 0 deletions utils/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package utils
import (
"fmt"
"io"
"os"
)

func PrintJSON(format string, a ...any) {
Expand Down Expand Up @@ -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...)
}

0 comments on commit 890bf92

Please sign in to comment.