feat: Add native Go 1.23 Iterator support by merchantmoh-debug · Pull Request #3916 · google/go-github
This PR introduces native Go 1.23 iterator support to the entire library via a new code generator.
The Problem
Pagination in go-github currently requires verbose boilerplate:
opt := &github.RepositoryListByUserOptions{ListOptions: github.ListOptions{PerPage: 10}} for { repos, resp, err := client.Repositories.ListByUser(ctx, "user", opt) // handle err for _, repo := range repos { ... } if resp.NextPage == 0 { break } opt.Page = resp.NextPage }
The Solution: With this PR, users can simply write:
for repo, err := range client.Repositories.ListByUserIter(ctx, "user", opt) { if err != nil { log.Fatal(err) } fmt.Println(repo.GetName()) }
Implementation Details
github/gen-iterators.go: A new AST-based tool (similar to gen-accessors) that scans all List* methods, identifies their pagination patterns (Page/Cursor), and generates a corresponding *Iter method returning iter.Seq2.
It handles methods using standard ListOptions embedding and explicit Page fields.
It copies the opts struct to avoid mutating the caller's options during iteration.
github/iterators.go: The generated file containing hundreds of type-safe iterators.
Metadata Handling: Updated tools/metadata to exclude the generated iterators from API operation mapping validation, as they wrap existing operations.
Testing & Benchmarks
github/iterators_benchmark_test.go confirms that the iterator abstraction introduces negligible overhead compared to manual looping.
github/iterators_test.go verifies single-page, multi-page, and error handling scenarios.
Tests explicitly verify that the user's opts struct is NOT mutated by the iterator.
Documentation
Added github/example_iterators_test.go to provide a clear example in the Godoc.
This modernizes the library to leverage the latest Go features, significantly improving Developer Experience (DX) by eliminating error-prone pagination boilerplate.