Home > Enterprise >  Unable to run https git clone using go-git and access token
Unable to run https git clone using go-git and access token

Time:12-05

Using go-git/v5 and trying to clone over https as follows:

    _, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
        URL:           repo,
        ReferenceName: plumbing.ReferenceName(branch),
        Depth:         1,
        SingleBranch:  true,
        Auth:          &http.TokenAuth{Token: string(token)},
    })

where token is a string of the form ghp_XXXXXXXXX (my personal GH access token)

and repo equals to my private repo https://github.com/pkaramol/arepo

The error is

"net/http: invalid header field value \"Bearer ghp_XXXXXXXXX`\\n\" for key Authorization"

I have also trying using basic auth with my username and the token as password

    _, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
        URL:           repo,
        ReferenceName: plumbing.ReferenceName(branch),
        Depth:         1,
        SingleBranch:  true,
        Auth:          &http.BasicAuth{Username: "pkaramol", Password: token},
    })

Now the error becomes:

authentication required

What is the proper way of cloning over https?

The token has repo scope fwiw

edit:

the fs is instantiated as follows

fs := memfs.New()

the http package used is the following

"github.com/go-git/go-git/v5/plumbing/transport/http"

CodePudding user response:

This should work:

package main

import (
    "os"
    "fmt"

    "github.com/go-git/go-billy/v5/memfs"
    "github.com/go-git/go-git/v5/plumbing"
    "github.com/go-git/go-git/v5/plumbing/transport/http"
    "github.com/go-git/go-git/v5/storage/memory"

    git "github.com/go-git/go-git/v5"
)

func main() {
    token := "ghp_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

    fs := memfs.New()

    _, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
        URL:           "https://github.com/username/reponame",
        ReferenceName: plumbing.ReferenceName("refs/heads/main"),
        Depth:         1,
        SingleBranch:  true,
        Auth:          &http.BasicAuth{Username: "username", Password: token},
        Progress:      os.Stdout,
    })

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Done")
}
  • Related