Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package api

import (
"net/http"
)

// FetchAllPages demonstrates the correct pagination loop logic.
func FetchAllPages(client *http.Client, initialURL string, limit int) ([]interface{}, error) {
var allResults []interface{}
currentURL := initialURL

for currentURL != "" && (limit <= 0 || len(allResults) < limit) {
req, _ := http.NewRequest("GET", currentURL, nil)
resp, err := client.Do(req)
if err != nil {
return nil, err
}

// ... logic to decode results ...
// results := decode(resp)
// allResults = append(allResults, results...)

currentURL = GetNextPageURL(resp.Header)
}
return allResults, nil
}
21 changes: 21 additions & 0 deletions api/paginator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package api

import (
"net/http"
"regexp"
)

var nextLinkRegex = regexp.MustCompile(`<(.*?)>; rel="next"`)

// GetNextPageURL extracts the next page URL from the Link header.
func GetNextPageURL(header http.Header) string {
link := header.Get("Link")
if link == "" {
return ""
}
matches := nextLinkRegex.FindStringSubmatch(link)
if len(matches) > 1 {
return matches[1]
}
return ""
}