获取 gitlab 回购列表:显示“401 未经授权”

Fetching gitlab repo list : says "401 Unauthorized"

我正在尝试使用 OAuth 令牌从 gitlab 获取回购列表。

我的代码看起来像这样... ("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 {message: 401 Unauthorized}

我对令牌值有信心,因为我正在使用相同的令牌获取回购的所有分支列表,该代码看起来像 ... ("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 adds in :

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)