登录
首页 >  Golang >  Go问答

从 GitHub Enterprise 中使用 go-git 克隆仓库

来源:stackoverflow

时间:2024-03-15 18:30:29 248浏览 收藏

使用 go-git 从 GitHub Enterprise 克隆存储库时,可能会遇到 400 响应错误。这是因为 GitHub Enterprise 需要使用基本身份验证,而不是标头中的令牌。正确的配置方式是使用 `http.BasicAuth` 结构,将令牌作为密码提供给 `Token` 字段。go-git 也支持使用令牌进行身份验证,但需要使用 `TokenAuth` 结构将其作为 `Auth` 选项传递。

问题内容

我正在尝试使用 go-git 从 github enterprise 克隆存储库。为此,我使用带有访问令牌的 https 协议,该令牌具有对我的存储库的适当权限(在命令行上验证)。 go-git 在进行 git-upload-pack rpc 调用时失败,因为服务器响应 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(匿名访问被拒绝 )响应。有了令牌,它就会响应 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)
}

解决方案


事实证明,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,
}

他们有能力使用令牌:

https://github.com/src-d/go-git/blob/master/plumbing/transport/http/common.go#L204-L227

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

func main() {
  ...
  auth := http.TokenAuth{Token: "TOKEN_HERE"}
  opts := git.CloneOptions{
    URL:  "https://github.com/user/repo",
    Auth: &auth,
  }
  git.PlainClone("/tmp/cloneDir", false, &opts)
  ..
}

不能 100% 确定这是否能解决您的所有问题

本篇关于《从 GitHub Enterprise 中使用 go-git 克隆仓库》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>