正在获取 gitlab 存储库列表:显示“401 Unauthorized”

Kev*_*ata 6 oauth go gitlab

我正在尝试使用 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
    }
Run Code Online (Sandbox Code Playgroud)

我无法获取项目列表..“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},
})
Run Code Online (Sandbox Code Playgroud)

这是否意味着我正在使用的库存在问题?github.com/xanzy/go-gitlab

Von*_*onC 3

这取决于您使用的令牌类型

例如,项目访问令牌很可能使您能够访问存储库(针对该项目)的所有分支的列表。

但对于使用/projectsAPI,401 意味着身份验证信息无效或丢失。

因此,请确保使用链接到用户而不是项目的PAT(个人访问令牌) 。


OP Keval Bhogayata在评论中补充道:

我已经找到问题了。

我正在使用的库(“ xanzy/go-gitlab”)对于不同的令牌具有不同的客户端创建功能。

我一直在使用支持个人访问令牌的功能。相反,我应该使用“ 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)
Run Code Online (Sandbox Code Playgroud)