From 526dcf6dcb4022313f9e59917ae92500d197e529 Mon Sep 17 00:00:00 2001 From: sneak Date: Mon, 20 May 2024 04:33:21 -0700 Subject: [PATCH] works --- main.go | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index b00ec79..9679bb8 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "os" + "time" ) // Card represents the structure of a card in the API response. @@ -159,8 +160,10 @@ func fetchCards(limit, cursor int) ([]*Card, error) { setHeaders(req) // Perform the HTTP request + start := time.Now() client := &http.Client{} resp, err := client.Do(req) + duration := time.Since(start) if err != nil { return nil, fmt.Errorf("failed to perform request: %w", err) } @@ -187,22 +190,26 @@ func fetchCards(limit, cursor int) ([]*Card, error) { } // Extract cards from the result + var cards []*Card if len(result) > 0 { - return result[0].Result.Data.JSON.Cards, nil + cards = result[0].Result.Data.JSON.Cards } - return nil, nil + fmt.Printf("Cursor: %d, Limit: %d, Duration: %s, Status: %d, Cards: %d\n", + cursor, limit, duration, resp.StatusCode, len(cards)) + + return cards, nil } -func main() { - const limit = 100 +// fetchAllCards fetches all cards by making multiple requests with different cursor values. +func fetchAllCards(limit int) ([]*Card, error) { var allCards []*Card cursor := 0 for { cards, err := fetchCards(limit, cursor) if err != nil { - logErrorAndExit(err) + return nil, err } allCards = append(allCards, cards...) @@ -216,6 +223,17 @@ func main() { cursor += limit } + return allCards, nil +} + +func main() { + const limit = 100 + + allCards, err := fetchAllCards(limit) + if err != nil { + logErrorAndExit(err) + } + // Write all cards to cards.json in the current working directory file, err := os.Create("cards.json") if err != nil { @@ -233,7 +251,7 @@ func main() { logErrorAndExit(fmt.Errorf("failed to write to cards.json: %w", err)) } - fmt.Println("All cards have been written to cards.json") + fmt.Printf("All cards have been written to cards.json. Total cards: %d\n", len(allCards)) } // setHeaders sets the necessary headers for the HTTP request. @@ -249,3 +267,4 @@ func logErrorAndExit(err error) { os.Exit(1) } +