Golang使用go-github库调用GitHub API的示例
Golang使用go-github库调用GitHub API的示例 大家好! 我正在尝试使用GithubLibrary库与GitHub进行交互 遇到了一些问题 如果我获取单个仓库信息,就无法使用处理该仓库所有问题的方法 当我尝试从特定仓库获取所有问题时,不知道如何正确设置不需要的选项值 例如:
myGHBClient := github.NewClient(tokenClient)
opt := &github.IssueListByRepoOptions{
Milestone:"",
State: "all",
Assignee: "",
Creator: "",
Mentioned: "",
Labels: []string{"bug"},
Sort: "",
Direction: "asc",
Since: "", // 我想获取所有问题而不考虑时间关系
// 但库要求我必须使用某种时间线
ListOptions: {0,0}, // 这里遇到了这样的问题
// 复合字面量中缺少类型
}
issue, _, err := myGHBClient.Issues.ListByRepo(context, "User", "Repo", opt)
我只是想从特定仓库获取所有问题,并按标签和状态进行筛选 我哪里做错了? 谢谢
更多关于Golang使用go-github库调用GitHub API的示例的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang使用go-github库调用GitHub API的示例的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在你的代码中,有几个地方需要修正才能正确使用 go-github 库。主要问题在于结构体字段的初始化和分页处理。以下是修正后的示例:
package main
import (
"context"
"fmt"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
func main() {
// 创建 GitHub 客户端
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "YOUR_GITHUB_TOKEN"},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// 设置查询选项
opt := &github.IssueListByRepoOptions{
State: "all",
Labels: []string{"bug"},
Direction: "asc",
ListOptions: github.ListOptions{
PerPage: 100, // 每页数量
},
}
var allIssues []*github.Issue
for {
issues, resp, err := client.Issues.ListByRepo(ctx, "owner", "repo", opt)
if err != nil {
fmt.Printf("Error: %v\n", err)
break
}
allIssues = append(allIssues, issues...)
// 检查是否还有下一页
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
// 处理获取到的问题
for _, issue := range allIssues {
fmt.Printf("Issue #%d: %s\n", *issue.Number, *issue.Title)
}
}
关键修正点:
- ListOptions 初始化:使用正确的结构体类型
github.ListOptions{} - 分页处理:通过循环处理所有页面,使用
resp.NextPage来获取下一页 - 空字段处理:对于不需要的字符串字段,直接省略即可(Go 会使用零值)
- 时间字段:
Since字段如果不需要时间过滤,直接不设置或设置为零值
如果你需要处理认证,这里是一个完整的认证示例:
// 使用个人访问令牌认证
func createClientWithToken(token string) *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}
// 或者使用基础认证
func createClientWithBasicAuth(username, password string) *github.Client {
tp := github.BasicAuthTransport{
Username: username,
Password: password,
}
return github.NewClient(tp.Client())
}
对于更复杂的筛选,你可以这样设置选项:
opt := &github.IssueListByRepoOptions{
State: "open", // "open", "closed", "all"
Labels: []string{"bug", "enhancement"},
Sort: "created", // "created", "updated", "comments"
Direction: "desc", // "asc" or "desc"
ListOptions: github.ListOptions{
PerPage: 50,
},
}
这样就能正确获取特定仓库的所有问题,并按标签和状态进行筛选了。

