我正在尝试使用 OAuth token 从 gitlab 获取 repo 列表。
我的代码看起来像这样......(“github.com/xanzy/go-gitlab”)
repositories := []string{}
client, _ := gitlab.NewClient(gitRepoRequest.Token, gitlab.WithBaseURL("https://gitlab.com/api/v4"))
fmt.Println("client...", client.ContainerRegistry)
projects, _, projectListErr := client.Projects.ListProjects(&gitlab.ListProjectsOptions{})
for _, project := range projects {
fmt.Println("ID===", project.ID)
fmt.Println("NAME===", project.Name)
}
if projectListErr != nil {
// return err
}
我无法获取项目列表..“projectListErr”说...
GET https://gitlab.com/api/v4/projects: 401 {消息:401 未经授权}
我对代币值(value)充满信心,因为我正在使用相同的代币获取 repo 的所有分支列表,该代码看起来像......(“github.com/go-git/go-git/v5”)
rem := git.NewRemote(gitMemory.NewStorage(), &gitConfig.RemoteConfig{
Name: "origin",
URLs: []string{gitBranchesRequest.Repository},
})
refs, listErr := rem.List(&git.ListOptions{
Auth: &gitHttp.BasicAuth{Username: gitUserName, Password: gitBranchesRequest.Token},
})
这是否意味着我使用的库有问题? github.com/xanzy/go-gitlab
最佳答案
这取决于 type of token you are using .
例如,project access token很可能会让您访问存储库(针对该项目)的所有分支列表。
但是对于使用/projects
API,401意味着身份验证信息无效或丢失。
所以一定要使用 PAT (Personal Access Token) ,链接到用户,而不是项目。
OP Keval Bhogayata添加 the comments :
I have found the issue.
The library I am using ("
xanzy/go-gitlab
"), has different client creation functions for different tokens.I have been using the function that supports personal access token. Instead I was supposed to use "
NewOAuthClient
" !// NewOAuthClient returns a new GitLab API client. To use API methods which // require authentication, provide a valid oauth token. func NewOAuthClient(token string, options ...ClientOptionFunc) (*Client, error)
关于go - 获取 gitlab repo 列表 : says "401 Unauthorized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70532432/