首页 > 解决方案 > 使用 go-git 从 GitHub Enterprise 克隆存储库

问题描述

我正在尝试使用go-git从 GitHub Enterprise 克隆存储库。为此,我使用带有访问令牌的 HTTPS 协议,该访问令牌对我的存储库具有适当的权限(在命令行上验证)。go-git进行 RPC 调用时失败,git-upload-pack因为服务器以 400 响应:

$ go run main.go
unexpected client error: unexpected requesting "https://github.mycompany.net/my-org/myrepo.git/info/refs?service=git-upload-pack" status code: 400

它发出的请求等价于:

GET /my-org/myrepo.git/info/refs?service=git-upload-pack HTTP/1.1
Host: github.mycompany.net
User-Agent: git/1.0
Accept: */*
Authorization: Bearer atokenthatisdefinitelyvalid

如果没有请求标头中的令牌,我会从存储库中获得预期的 401 ( Anonymous access denied) 响应。使用令牌,它会以 400 响应。

我发现非企业 GitHub 上的公共存储库也是如此;不同之处在于它(预期)在没有Authorization标题的情况下工作,因为没有必要。如果我包含一个有效的令牌,GitHub 就像它的企业版一样以 400 响应。

下面是一个最小的例子。有没有一种方法可以go-git与需要身份验证的 GitHub Enterprise 一起使用?理想情况下使用身份验证令牌?

package main

import (
    "fmt"
    "io/ioutil"

    git "gopkg.in/src-d/go-git.v4"
    "gopkg.in/src-d/go-git.v4/plumbing"
    "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
)

const (
    repoURL           = "https://github.mycompany.net/my-org/myrepo.git"
    githubAccessToken = "atokenthatisdefinitelyvalid"
)

func main() {
    dir, _ := ioutil.TempDir("", "temp_dir")

    options := &git.CloneOptions{
        Auth:          &http.TokenAuth{Token: githubAccessToken},
        URL:           repoURL,
        Depth:         500,
        ReferenceName: plumbing.ReferenceName("refs/heads/master"),
        SingleBranch:  true,
        Tags:          git.NoTags,
    }

    _, err := git.PlainClone(dir, false, options)
    fmt.Println(err)
}

标签: gitgogithubgo-git

解决方案


事实证明,Github 使用令牌作为用户的密码,因此它需要基本身份验证而不是标头中的令牌:

options := &git.CloneOptions{
    Auth:          &http.BasicAuth{Username: "myusername", Token: "mytoken"},
    URL:           repoURL,
    Depth:         500,
    ReferenceName: plumbing.ReferenceName("refs/heads/master"),
    SingleBranch:  true,
    Tags:          git.NoTags,
}

推荐阅读