• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang oauth2.StaticTokenSource函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/oauth2.StaticTokenSource函数的典型用法代码示例。如果您正苦于以下问题:Golang StaticTokenSource函数的具体用法?Golang StaticTokenSource怎么用?Golang StaticTokenSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了StaticTokenSource函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: GenerateGithub

func GenerateGithub(name string, token string, exclude string) map[string]*Repo {
	repos := make(map[string]*Repo)

	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := github.NewClient(tc)
	opt := &github.RepositoryListByOrgOptions{
		Type:        "all",
		ListOptions: github.ListOptions{PerPage: 100},
	}

	for {
		newRepos, resp, err := client.Repositories.ListByOrg(name, opt)
		check(err)

		for _, newRepo := range newRepos {
			url := fmt.Sprintf("[email protected]:%s/%s.git", name, *newRepo.Name)
			repos[*newRepo.Name] = &Repo{
				Url: url,
			}
		}

		if resp.NextPage == 0 {
			break
		}
		opt.ListOptions.Page = resp.NextPage
	}

	return repos
}
开发者ID:nyxcharon,项目名称:hound,代码行数:30,代码来源:github_org.go


示例2: RegisterResult

//RegisterResult registers the supplied result
func (githubClient *GitHubClient) RegisterResult(result Result) error {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: githubClient.Token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := github.NewClient(tc)

	if githubClient.BaseUrl != nil {
		client.BaseURL = githubClient.BaseUrl
	}

	log.Info("Submitting result")
	repositories := client.Repositories
	status, _, err := repositories.CreateStatus(
		githubClient.From,
		githubClient.Repo,
		result.SHA,
		&github.RepoStatus{
			State:       github.String(result.State),
			TargetURL:   github.String(result.Url),
			Description: github.String(result.Message),
			Context:     github.String("continuous-integraion/walter"),
		})
	log.Infof("Submit status: %s", status)
	if err != nil {
		log.Errorf("Failed to register result: %s", err)
	}
	return err
}
开发者ID:FabianFrancoRoldan,项目名称:walter,代码行数:30,代码来源:github.go


示例3: main

func main() {
	flag.Usage = usage
	flag.Parse()
	cachingHTTPClient = util.CachingHttpClient()

	if *tokenFlag == "" || cachingHTTPClient == nil {
		flag.Usage()
		return
	}

	ds = clientFlags.CreateDataset()
	if ds == nil {
		flag.Usage()
		return
	}
	defer ds.Store().Close()

	if err := clientFlags.CreateProgressFile(); err != nil {
		fmt.Println(err)
	} else {
		defer clientFlags.CloseProgressFile()
	}

	token := oauth2.Token{AccessToken: *tokenFlag}
	authHTTPClient = oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(&token))

	start = time.Now()
	var user = getUser()
	printStats(user)

	userRef := ds.Store().WriteValue(user)
	fmt.Printf("userRef: %s\n", userRef.TargetRef())
	_, err := ds.Commit(userRef)
	d.Exp.NoError(err)
}
开发者ID:arv,项目名称:noms-old,代码行数:35,代码来源:facebook.go


示例4: getClient

func (d *Driver) getClient() *godo.Client {
	token := &oauth2.Token{AccessToken: d.AccessToken}
	tokenSource := oauth2.StaticTokenSource(token)
	client := oauth2.NewClient(oauth2.NoContext, tokenSource)

	return godo.NewClient(client)
}
开发者ID:mschygulla,项目名称:machine,代码行数:7,代码来源:digitalocean.go


示例5: getClient

func getClient(token string) *github.Client {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	return github.NewClient(tc)
}
开发者ID:cgcgbcbc,项目名称:umeng2github,代码行数:7,代码来源:github.go


示例6: gistHandler

func gistHandler(w http.ResponseWriter, r *http.Request) {
	log.Debug("gistHandler()")

	// get access token
	c, err := r.Cookie("access_token")
	if err != nil {
		log.Error("get cookie error: ", err)
		http.Error(w, "Github Auth Error", http.StatusInternalServerError)
		return
	}

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: c.Value},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	// github api
	client := github.NewClient(tc)

	gist, err := makeGist(r.Body)
	if err != nil {
		log.Errorf("make gist error: %v", err)
		http.Error(w, "Server Error", http.StatusInternalServerError)
		return
	}

	retGist, _, err := client.Gists.Create(&gist)
	if err != nil {
		log.Error("create gist error: ", err)
		http.Error(w, "Post Gist Error", http.StatusInternalServerError)
		return
	}

	io.WriteString(w, *retGist.HTMLURL)
}
开发者ID:178inaba,项目名称:go-plgr2gist,代码行数:35,代码来源:gist.go


示例7: retrieveCommits

// retrieveCommits fetches the latest deployed commits as well
// as the latest GitHub commits for a given Project.
// it will also check if the user has permission to pull.
func retrieveCommits(r *http.Request, project goship.Project, deployUser string) (goship.Project, error) {
	// define a wait group to wait for all goroutines to finish
	var wg sync.WaitGroup
	githubToken := os.Getenv(gitHubAPITokenEnvVar)
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: githubToken})
	client := github.NewClient(oauth2.NewClient(oauth2.NoContext, ts))
	for i, environment := range project.Environments {
		for j, host := range environment.Hosts {
			// start a goroutine for SSHing on to the machine
			wg.Add(1)
			go getCommit(&wg, project, environment, host, deployUser, i, j)
		}
		wg.Add(1)
		go getLatestGitHubCommit(&wg, project, environment, client, project.RepoOwner, project.RepoName, i)
	}
	// wait for goroutines to finish
	wg.Wait()
	for i, e := range project.Environments {

		project.Environments[i] = e
		for j, host := range e.Hosts {
			host.GitHubCommitURL = host.LatestGitHubCommitURL(project)
			host.GitHubDiffURL = host.LatestGitHubDiffURL(project, e)
			host.ShortCommitHash = host.LatestShortCommitHash()
			project.Environments[i].Hosts[j] = host
		}
	}
	u, err := getUser(r)
	if err != nil {
		log.Printf("Failed to get user %s", err)
	}
	return filterProject(project, r, u), err
}
开发者ID:cinderalla,项目名称:goship,代码行数:36,代码来源:goship.go


示例8: create

func create(desc string, pub bool, files map[string]string) (*github.Gist, error) {

	ghat := getAccessToken()

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: ghat},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	client := github.NewClient(tc)

	f := make(map[github.GistFilename]github.GistFile)

	for k := range files {
		_k := github.GistFilename(k)
		f[_k] = github.GistFile{Content: github.String(files[k])}
	}

	gist := &github.Gist{
		Description: github.String(desc),
		Public:      github.Bool(pub),
		Files:       f,
	}

	gist, _, err := client.Gists.Create(gist)

	return gist, err
}
开发者ID:chanux,项目名称:gogist,代码行数:28,代码来源:main.go


示例9: initializeClient

func initializeClient(token string) {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client = github.NewClient(tc)
}
开发者ID:f2prateek,项目名称:github-gender-stats,代码行数:7,代码来源:main.go


示例10: Login

// Logs in to github using oauth.
// Returns error if login fails.
func Login(userkey string) error {
	file, err := ioutil.ReadFile(*Path + ".issue/config.json")
	if err != nil {
		GitLog.Println("open config: ", err)
		os.Exit(1)
	}
	temp := new(Config)
	if err = json.Unmarshal(file, temp); err != nil {
		GitLog.Println("parse config: ", err)
		os.Exit(1)
	}
	Conf = temp
	token := Conf.Token
	if Conf.Secure {
		key := []byte(userkey)
		token = encrypt.Decrypt(key, token)
	}
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client = github.NewClient(tc)
	user, _, err := client.Users.Get("")

	if err != nil {
		GitLog.Printf("\nerror: %v\n", err)
		return err
	}
	log.Printf("\nLogged into: %v\n", github.Stringify(user.Login))
	GitLog.Print("Logged into: ", github.Stringify(user.Login))
	return nil
}
开发者ID:butlerx,项目名称:AgileGit,代码行数:34,代码来源:gitissue.go


示例11: BuildHTTPClient

func BuildHTTPClient(proxy, token string) *http.Client {
	var base http.RoundTripper
	base = http.DefaultTransport

	// Proxy layer
	if len(proxy) > 0 {
		u, _ := url.Parse(proxy)
		base = &http.Transport{
			Proxy: http.ProxyURL(u),
		}
	}

	// Authentication layer
	if len(token) > 0 {
		ts := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: token},
		)
		base = &oauth2.Transport{
			Source: ts,
			Base:   base,
		}
	}

	// Rate limiting
	transport := &RateLimitedTransport{
		Base: base,
	}

	return &http.Client{
		Transport: transport,
	}
}
开发者ID:mmcloughlin,项目名称:ghr,代码行数:32,代码来源:main.go


示例12: cmdSetup

func cmdSetup(c *cli.Context) {
	token := c.Args().First()

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := qiita.NewClient(tc)
	user, err := client.AuthenticatedUser.Show()
	if err != nil {
		fmt.Println("Auth failed")
		os.Exit(1)
	}

	loadConfig()
	viper.Set("accessToken", token)
	viper.Set("id", user.Id)

	err = saveConfig()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println("Token saved")
}
开发者ID:uetchy,项目名称:alfred-qiita-workflow,代码行数:26,代码来源:setup.go


示例13: NewClient

// NewClient returns a new BitBalloon API client
func NewClient(config *Config) *Client {
	client := &Client{}

	if config.BaseUrl != "" {
		client.BaseUrl, _ = url.Parse(config.BaseUrl)
	} else {
		client.BaseUrl, _ = url.Parse(defaultBaseURL)
	}

	if config.HttpClient != nil {
		client.client = config.HttpClient
	} else if config.AccessToken != "" {
		client.client = oauth2.NewClient(
			oauth2.NoContext,
			oauth2.StaticTokenSource(
				&oauth2.Token{
					AccessToken: config.AccessToken,
				},
			),
		)
	}

	if &config.UserAgent != nil {
		client.UserAgent = config.UserAgent
	} else {
		client.UserAgent = userAgent
	}

	client.Sites = &SitesService{client: client}
	client.Deploys = &DeploysService{client: client}

	return client
}
开发者ID:BitBalloon,项目名称:bitballoon-go,代码行数:34,代码来源:bitballoon.go


示例14: createGithubClient

func (grp githubRegistryProvider) createGithubClient(credentialName string) (*http.Client, *github.Client, error) {
	if credentialName == "" {
		return http.DefaultClient, github.NewClient(nil), nil
	}
	c, err := grp.cp.GetCredential(credentialName)

	if err != nil {
		log.Printf("Failed to fetch credential %s: %v", credentialName, err)
		log.Print("Trying to use unauthenticated client")
		return http.DefaultClient, github.NewClient(nil), nil
	}

	if c != nil {
		if c.APIToken != "" {
			ts := oauth2.StaticTokenSource(
				&oauth2.Token{AccessToken: string(c.APIToken)},
			)
			tc := oauth2.NewClient(oauth2.NoContext, ts)
			return tc, github.NewClient(tc), nil
		}
		if c.BasicAuth.Username != "" && c.BasicAuth.Password != "" {
			tp := github.BasicAuthTransport{
				Username: c.BasicAuth.Username,
				Password: c.BasicAuth.Password,
			}
			return tp.Client(), github.NewClient(tp.Client()), nil
		}

	}
	return nil, nil, fmt.Errorf("No suitable credential found for %s", credentialName)

}
开发者ID:danielckv,项目名称:deployment-manager,代码行数:32,代码来源:registryprovider.go


示例15: GetClient

func GetClient() *godo.Client {
	token := &oauth2.Token{AccessToken: token}
	t := oauth2.StaticTokenSource(token)

	oauthClient := oauth2.NewClient(oauth2.NoContext, t)
	return godo.NewClient(oauthClient)
}
开发者ID:carriercomm,项目名称:doenv,代码行数:7,代码来源:lib.go


示例16: downloadReleaseFromGithub

func downloadReleaseFromGithub(r repo, artifact string, alias string) {
	client := github.NewClient(nil)

	config, err := loadConfig()
	if err != nil {
		DieWithError(err, "Could not load user config")
	}

	if token, ok := config.Config["token"]; ok {
		log.Debug("Using Github token from config.")
		// if the user has a token stored, use it
		ts := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: token},
		)
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		client = github.NewClient(tc)
	} else {
		log.Debug("No Github token found in config. Add it with `mup config` if you need it")
	}

	// with a provided token, this will also get repos for the authenticated user
	// TODO: support pagination
	releases, resp, err := client.Repositories.ListReleases(r.Owner, r.Repo, nil)
	if resp.StatusCode == 404 {
		Die("Could not find repository %s/%s. Maybe it doesn't exist, or you need to add your token for μpdater to have access.", r.Owner, r.Repo)
	} else if err != nil {
		DieWithError(err, "Error reaching Github")
	}

	updateFromGithubReleases(client, r, releases, "", artifact, alias)
}
开发者ID:jordanti,项目名称:mupdater,代码行数:31,代码来源:apps.go


示例17: getLatestVersionFromGitHub

// borrowed from minishift until it supports install / download binaries
func getLatestVersionFromGitHub(githubOwner, githubRepo string) (semver.Version, error) {
	if githubClient == nil {
		token := os.Getenv("GH_TOKEN")
		var tc *http.Client
		if len(token) > 0 {
			ts := oauth2.StaticTokenSource(
				&oauth2.Token{AccessToken: token},
			)
			tc = oauth2.NewClient(oauth2.NoContext, ts)
		}
		githubClient = github.NewClient(tc)
	}
	client := githubClient
	var (
		release *github.RepositoryRelease
		resp    *github.Response
		err     error
	)
	release, resp, err = client.Repositories.GetLatestRelease(githubOwner, githubRepo)
	if err != nil {
		return semver.Version{}, err
	}
	defer resp.Body.Close()
	latestVersionString := release.TagName
	if latestVersionString != nil {
		return semver.Make(strings.TrimPrefix(*latestVersionString, "v"))

	}
	return semver.Version{}, fmt.Errorf("Cannot get release name")
}
开发者ID:gashcrumb,项目名称:gofabric8,代码行数:31,代码来源:install.go


示例18: insertEntry

func insertEntry(env, owner, repoName, fromRevision, toRevision, user string, success bool, time time.Time) error {
	path := path.Join(*dataPath, env+".json")
	err := prepareDataFiles(path)
	if err != nil {
		return err
	}

	e, err := readEntries(env)
	if err != nil {
		return err
	}
	gt := os.Getenv(gitHubAPITokenEnvVar)
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: gt})
	c := github.NewClient(oauth2.NewClient(oauth2.NoContext, ts))
	com, _, err := c.Git.GetCommit(owner, repoName, toRevision)
	if err != nil {
		log.Println("Error getting commit msg: ", err)
	}
	var m string
	if com.Message != nil {
		m = *com.Message
	}
	diffURL := diffURL(owner, repoName, fromRevision, toRevision)
	d := DeployLogEntry{DiffURL: diffURL, ToRevisionMsg: m, User: user, Time: time, Success: success}
	e = append(e, d)
	err = writeJSON(e, path)
	if err != nil {
		return err
	}
	return nil
}
开发者ID:cinderalla,项目名称:goship,代码行数:31,代码来源:goship.go


示例19: newSlackServer

// newSlackServer returns an http handler for handling Slack slash commands at <url>/slack.
func newSlackServer(q conveyor.BuildQueue, c *cli.Context) http.Handler {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: c.String("github.token")},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	cy := github.NewClient(tc)

	r := slash.NewMux()
	r.Match(slash.MatchSubcommand(`help`), slack.Help)
	r.MatchText(
		regexp.MustCompile(`enable (?P<owner>\S+?)/(?P<repo>\S+)`),
		slack.NewEnable(
			cy,
			slack.NewHook(c.String("url"), c.String("github.secret")),
		),
	)
	r.MatchText(
		regexp.MustCompile(`build (?P<owner>\S+?)/(?P<repo>\S+)@(?P<branch>\S+)`),
		slack.NewBuild(
			cy,
			q,
			fmt.Sprintf(logsURLTemplate, c.String("url")),
		),
	)

	return slash.NewServer(slash.ValidateToken(r, c.String("slack.token")))
}
开发者ID:emmetog,项目名称:conveyor,代码行数:29,代码来源:factories.go


示例20: getVersions

func getVersions() ([]*github.RepositoryRelease, error) {
	if githubClient == nil {
		token := os.Getenv("GH_TOKEN")
		var tc *http.Client
		if len(token) > 0 {
			ts := oauth2.StaticTokenSource(
				&oauth2.Token{AccessToken: token},
			)
			tc = oauth2.NewClient(oauth2.NoContext, ts)
		}
		githubClient = github.NewClient(tc)
	}
	client := githubClient

	releases, resp, err := client.Repositories.ListReleases(githubOwner, githubRepo, nil)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if len(releases) == 0 {
		return nil, fmt.Errorf("There were no OpenShift Releases available")
	}
	return releases, nil
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:25,代码来源:openshift_versions.go



注:本文中的golang.org/x/oauth2.StaticTokenSource函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang oauth2.Config类代码示例发布时间:2022-05-28
下一篇:
Golang oauth2.ReuseTokenSource函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap