使用个人访问令牌(API令牌),通过OAuth2在GoLang中获取新的GitHub客户端。

huangapple go评论86阅读模式
英文:

GoLang github get new client with oauth2 by using persona access token (API TOKEN)

问题

我正在尝试使用以下简单代码列出存储库,但出现了403错误,错误提示为bad credentials。我认为问题在于我有自定义的Github URL https://github.mycompany.io。有人能建议我如何解决这个问题吗?因为我对Go语言还很陌生。

import (
	"golang.org/x/oauth2"
	"github.com/google/go-github/github"
)

func main() {
	ctx := context.Background()
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: "MY GITHUB STATIC TOKEN"},
	)
	tc := oauth2.NewClient(ctx, ts)

	client := github.NewClient(tc)

	//列出认证用户的所有存储库
	repos, _, err := client.Repositories.List(ctx, "", nil)
}
英文:

I am trying to list repos by using following simple code, It gives 403 bad credentials error, I think the problem is that I have custom Github Url https://github.mycompany.io
Can someone suggest how I can solve this since i am quite new to Go.

import(
 "golang.org/x/oauth2"
 "github.com/google/go-github/github"
)
func main() {
	ctx := context.Background()
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: "MY GITHUB STATIC TOKEN"},
	)
	tc := oauth2.NewClient(ctx, ts)

	client := github.NewClient(tc)

	//list all repositories for the authenticated user
	repos, _, err := client.Repositories.List(ctx, "", nil)
}

答案1

得分: 2

你是否尝试过使用NewEnterpriseClient()函数,因为你正在使用托管的 GitHub?

请参考链接:https://github.com/google/go-github/blob/f5943dbb9a7a560d3894701dbe3481f81886393a/github/github_test.go#L269

英文:

Since you are using a hosted github have you tried NewEnterpriseClient()?

see https://github.com/google/go-github/blob/f5943dbb9a7a560d3894701dbe3481f81886393a/github/github_test.go#L269

huangapple
  • 本文由 发表于 2022年1月4日 23:26:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/70581181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定