get ALL repos
Marco Andronaco andronacomarco@gmail.com
Fri, 14 Jun 2024 03:00:59 +0200
1 files changed,
35 insertions(+),
23 deletions(-)
jump to
M
main.go
→
main.go
@@ -20,35 +20,47 @@ Description string `json:"description"`
} func getRepos(username, token string) ([]Repo, error) { - url := fmt.Sprintf("https://api.github.com/users/%s/repos", username) - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - req.SetBasicAuth(username, token) + var allRepos []Repo + page := 1 - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() + for { + url := fmt.Sprintf("https://api.github.com/users/%s/repos?page=%d&per_page=100", username, page) + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + req.SetBasicAuth(username, token) - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("failed to fetch repositories: %s", resp.Status) - } + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("failed to fetch repositories: %s", resp.Status) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var repos []Repo + if err := json.Unmarshal(body, &repos); err != nil { + return nil, err + } - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } + if len(repos) == 0 { + break + } - var repos []Repo - if err := json.Unmarshal(body, &repos); err != nil { - return nil, err + allRepos = append(allRepos, repos...) + page++ } - return repos, nil + return allRepos, nil } func runGitCommand(args ...string) error {