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

Golang oauth2.NewClient函数代码示例

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

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



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

示例1: main

func main() {
	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("build", &build)
	plugin.Param("repo", &repo)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()
	sort.Strings(vargs.Gzip) // need for matchGzip

	// context for all clients
	ctx := context.Background()
	// GitHub client
	gts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vargs.GitHubToken})
	client.ghub = github.NewClient(oauth2.NewClient(ctx, gts))
	// GCS client
	auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl)
	if err != nil {
		fatalf("auth: %v", err)
	}
	tsrc := auth.TokenSource(ctx)
	client.gcs, err = storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx)))
	if err != nil {
		fatalf("storage client: %v", err)
	}
	// http client with service account authorization
	client.http = oauth2.NewClient(ctx, tsrc)

	run()
	if ecode != 0 {
		msg := fmt.Sprintf("exited with code %d", ecode)
		updateStatus("error", msg, stagingURL)
	}
	os.Exit(ecode)
}
开发者ID:peterwang1996,项目名称:WebFundamentals,代码行数:34,代码来源:main.go


示例2: NewClient

// NewClient returns a new client
func NewClient(config *Config) (client *Client, err error) {
	// bootstrap the config
	defConfig := DefaultConfig()

	if len(config.ApiAddress) == 0 {
		config.ApiAddress = defConfig.ApiAddress
	}

	if len(config.Username) == 0 {
		config.Username = defConfig.Username
	}

	if len(config.Password) == 0 {
		config.Password = defConfig.Password
	}

	if len(config.Token) == 0 {
		config.Token = defConfig.Token
	}

	ctx := oauth2.NoContext
	if config.SkipSslValidation == false {
		ctx = context.WithValue(ctx, oauth2.HTTPClient, defConfig.HttpClient)
	} else {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{Transport: tr})
	}

	endpoint, err := getInfo(config.ApiAddress, oauth2.NewClient(ctx, nil))

	if err != nil {
		return nil, fmt.Errorf("Could not get api /v2/info: %v", err)
	}

	authConfig := &oauth2.Config{
		ClientID: "cf",
		Scopes:   []string{""},
		Endpoint: oauth2.Endpoint{
			AuthURL:  endpoint.AuthEndpoint + "/oauth/auth",
			TokenURL: endpoint.TokenEndpoint + "/oauth/token",
		},
	}

	token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)

	if err != nil {
		return nil, fmt.Errorf("Error getting token: %v", err)
	}

	config.TokenSource = authConfig.TokenSource(ctx, token)
	config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)

	client = &Client{
		config:   *config,
		Endpoint: *endpoint,
	}
	return client, nil
}
开发者ID:dingotiles,项目名称:dingo-postgresql-broker,代码行数:61,代码来源:client.go


示例3: mainhandler

func mainhandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	ctx := appengine.NewContext(r)
	//src := google.AppEngineTokenSource(ctx, oauthsvc.UserinfoEmailScope)
	src, err := google.DefaultTokenSource(ctx, oauthsvc.UserinfoEmailScope)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	client := &http.Client{
		Transport: &oauth2.Transport{
			Source: src,
			Base:   &urlfetch.Transport{Context: ctx},
		},
	}
	client = oauth2.NewClient(ctx, src)
	service, err := oauthsvc.New(client)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	ui, err := service.Userinfo.Get().Do()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	log.Infof(ctx, "UserInfo: %v", ui.Email)
	fmt.Fprintln(w, "UserInfo: ", ui.Email)
}
开发者ID:salrashid123,项目名称:gcpsamples,代码行数:26,代码来源:main.go


示例4: GetOauthClient

func GetOauthClient(token string) *http.Client {
	tokenSource := &TokenSource{
		AccessToken: token,
	}

	return oauth2.NewClient(oauth2.NoContext, tokenSource)
}
开发者ID:shawntoffel,项目名称:GoDoDdns,代码行数:7,代码来源:auth.go


示例5: 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


示例6: init

func init() {
	flag.BoolVar(&isVerbose, "v", false, "")
	flag.BoolVar(&isVerbose, "verbose", false, "")
	flag.Usage = func() {
		fmt.Println(path.Base(os.Args[0]), "- Print DNSPOD table changes")
		fmt.Println()
		fmt.Println("Options:")
		fmt.Println("    -v, --verbose    Show more output")
		fmt.Println()
		fmt.Println("Source: https://github.com/caiguanhao/dnspodd")
	}
	flag.Parse()

	githubClient = github.NewClient(oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: string(GITHUB_TOKEN)},
	)))

	if PROXY_URL != "" {
		proxy, err := url.Parse(PROXY_URL)
		if err == nil {
			http.DefaultTransport = &http.Transport{
				Proxy: func(req *http.Request) (*url.URL, error) {
					if req.URL.Host == "api.github.com" {
						return proxy, nil
					}
					return nil, nil
				},
			}
		}
	}
}
开发者ID:caiguanhao,项目名称:dnspodd,代码行数:31,代码来源:dnspodd.go


示例7: init

func init() {
	bucket := os.Getenv("REGISTRY_STORAGE_GCS_BUCKET")
	credentials := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")

	// Skip GCS storage driver tests if environment variable parameters are not provided
	skipGCS = func() string {
		if bucket == "" || credentials == "" {
			return "The following environment variables must be set to enable these tests: REGISTRY_STORAGE_GCS_BUCKET, GOOGLE_APPLICATION_CREDENTIALS"
		}
		return ""
	}

	if skipGCS() != "" {
		return
	}

	root, err := ioutil.TempDir("", "driver-")
	if err != nil {
		panic(err)
	}
	defer os.Remove(root)
	var ts oauth2.TokenSource
	var email string
	var privateKey []byte

	ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl)
	if err != nil {
		// Assume that the file contents are within the environment variable since it exists
		// but does not contain a valid file path
		jwtConfig, err := google.JWTConfigFromJSON([]byte(credentials), storage.ScopeFullControl)
		if err != nil {
			panic(fmt.Sprintf("Error reading JWT config : %s", err))
		}
		email = jwtConfig.Email
		privateKey = []byte(jwtConfig.PrivateKey)
		if len(privateKey) == 0 {
			panic("Error reading JWT config : missing private_key property")
		}
		if email == "" {
			panic("Error reading JWT config : missing client_email property")
		}
		ts = jwtConfig.TokenSource(ctx.Background())
	}

	gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) {
		parameters := driverParameters{
			bucket:        bucket,
			rootDirectory: root,
			email:         email,
			privateKey:    privateKey,
			client:        oauth2.NewClient(ctx.Background(), ts),
		}

		return New(parameters)
	}

	testsuites.RegisterSuite(func() (storagedriver.StorageDriver, error) {
		return gcsDriverConstructor(root)
	}, skipGCS)
}
开发者ID:dalsh,项目名称:distribution,代码行数:60,代码来源:gcs_test.go


示例8: NewProtoClient

// NewProtoClient returns a ProtoClient for communicating with a Google cloud service,
// configured with the given ClientOptions.
func NewProtoClient(ctx context.Context, opt ...cloud.ClientOption) (*ProtoClient, error) {
	var o opts.DialOpt
	for _, opt := range opt {
		opt.Resolve(&o)
	}
	if o.GRPCClient != nil {
		return nil, errors.New("unsupported GRPC base transport specified")
	}
	var client *http.Client
	switch {
	case o.HTTPClient != nil:
		if o.TokenSource != nil {
			return nil, errors.New("at most one of WithTokenSource or WithBaseHTTP may be provided")
		}
		client = o.HTTPClient
	case o.TokenSource != nil:
		client = oauth2.NewClient(ctx, o.TokenSource)
	default:
		var err error
		client, err = google.DefaultClient(ctx, o.Scopes...)
		if err != nil {
			return nil, err
		}
	}

	return &ProtoClient{
		client:    client,
		endpoint:  o.Endpoint,
		userAgent: o.UserAgent,
	}, nil
}
开发者ID:Celluliodio,项目名称:flannel,代码行数:33,代码来源:dial.go


示例9: 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


示例10: DefaultClient

// DefaultClient returns an HTTP Client that uses the
// DefaultTokenSource to obtain authentication credentials.
//
// This client should be used when developing services
// that run on Google App Engine or Google Compute Engine
// and use "Application Default Credentials."
//
// For more details, see:
// https://developers.google.com/accounts/docs/application-default-credentials
//
func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
	ts, err := DefaultTokenSource(ctx, scope...)
	if err != nil {
		return nil, err
	}
	return oauth2.NewClient(ctx, ts), nil
}
开发者ID:fclairamb,项目名称:drone,代码行数:17,代码来源:default.go


示例11: New

// New returns a new instance of DoImages
func New(conf *DoConfig) (*DoImages, error) {
	if conf.Token == "" {
		return nil, errors.New("Access Token is not set. Please check your configuration.")
	}

	// increase the timeout
	timeout := time.Second * 30
	client := &http.Client{
		Transport: &http.Transport{TLSHandshakeTimeout: timeout},
		Timeout:   timeout,
	}

	// we need to pass the client with the context itself
	ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, client)

	oauthClient := oauth2.NewClient(ctx, &tokenSource{
		AccessToken: conf.Token,
	})

	godoClient := godo.NewClient(oauthClient)

	return &DoImages{
		client: godoClient,
		images: make([]godo.Image, 0),
	}, nil
}
开发者ID:hanscj1,项目名称:images,代码行数:27,代码来源:do.go


示例12: VerifyCredential

// VerifyCredential verifies whether the users DO credentials (access token) is
// valid or not
func (s *Stack) VerifyCredential(c *stack.Credential) error {
	cred := c.Credential.(*Credential)

	if err := cred.Valid(); err != nil {
		return err
	}

	oauthClient := oauth2.NewClient(
		oauth2.NoContext,
		oauth2.StaticTokenSource(&oauth2.Token{AccessToken: cred.AccessToken}),
	)

	client := godo.NewClient(oauthClient)

	// let's retrieve our Account information. If it's successful, we're good
	// to go
	_, _, err := client.Account.Get()
	if err != nil {
		return &stack.Error{
			Err: err,
		}
	}

	return nil
}
开发者ID:koding,项目名称:koding,代码行数:27,代码来源:stack.go


示例13: authWithGitHub

func authWithGitHub(tkn string) *github.Client {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: tkn},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	return github.NewClient(tc)
}
开发者ID:promiseofcake,项目名称:merged-prs,代码行数:7,代码来源:auth.go


示例14: doConfig

// Reads google storage config and creates a Client.  Exits on error.
func doConfig(t *testing.T) (gsa *Client, bucket string) {
	if *gsConfigPath == "" {
		t.Skip("Skipping manual test. Set flag --gs_config_path to test Google Storage.")
	}

	cf, err := osutil.NewJSONConfigParser().ReadFile(*gsConfigPath)
	if err != nil {
		t.Fatalf("Failed to read config: %v", err)
	}

	var config jsonconfig.Obj
	config = cf.RequiredObject("gsconf")
	if err := cf.Validate(); err != nil {
		t.Fatalf("Invalid config: %v", err)
	}

	auth := config.RequiredObject("auth")
	bucket = config.RequiredString("bucket")
	if err := config.Validate(); err != nil {
		t.Fatalf("Invalid config: %v", err)
	}

	gsa = NewClient(oauth2.NewClient(oauth2.NoContext, oauthutil.NewRefreshTokenSource(&oauth2.Config{
		Scopes:       []string{Scope},
		Endpoint:     google.Endpoint,
		ClientID:     auth.RequiredString("client_id"),
		ClientSecret: auth.RequiredString("client_secret"),
		RedirectURL:  oauthutil.TitleBarRedirectURL,
	}, auth.RequiredString("refresh_token"))))

	if err := auth.Validate(); err != nil {
		t.Fatalf("Invalid config: %v", err)
	}
	return
}
开发者ID:rfistman,项目名称:camlistore,代码行数:36,代码来源:googlestorage_test.go


示例15: 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


示例16: maybeRemapCloudSQL

func maybeRemapCloudSQL(host string) (out string, err error) {
	if !strings.HasSuffix(host, cloudSQLSuffix) {
		return host, nil
	}
	inst := strings.TrimSuffix(host, cloudSQLSuffix)
	if !metadata.OnGCE() {
		return "", errors.New("CloudSQL support only available when running on Google Compute Engine.")
	}
	proj, err := metadata.ProjectID()
	if err != nil {
		return "", fmt.Errorf("Failed to lookup GCE project ID: %v", err)
	}

	admin, _ := sqladmin.New(oauth2.NewClient(context.Background(), google.ComputeTokenSource("")))
	listRes, err := admin.Instances.List(proj).Do()
	if err != nil {
		return "", fmt.Errorf("error enumerating Cloud SQL instances: %v", err)
	}
	for _, it := range listRes.Items {
		if !strings.EqualFold(it.Instance, inst) {
			continue
		}
		js, _ := json.Marshal(it)
		log.Printf("Found Cloud SQL instance %s: %s", inst, js)
		for _, ipm := range it.IpAddresses {
			return ipm.IpAddress, nil
		}
		return "", fmt.Errorf("No external IP address for Cloud SQL instances %s", inst)
	}
	var found []string
	for _, it := range listRes.Items {
		found = append(found, it.Instance)
	}
	return "", fmt.Errorf("Cloud SQL instance %q not found. Found: %q", inst, found)
}
开发者ID:camarox53,项目名称:coreos-baremetal,代码行数:35,代码来源:cloudsql.go


示例17: Authenticate

func (gh *Client) Authenticate(username string, password string) error {
	var token []byte
	gh.User = &User{
		Login:    username,
		Password: password,
	}

	// conf := &oauth2.Config{
	// 	Endpoint: githubOauth2.Endpoint,
	// }
	gh.Store.Get(s.ConfigBucket, "gh_token", &token)
	if len(token) == 0 {
		var err error
		token, err = gh.createToken()
		if err != nil {
			return errwrap.Wrapf("[Github] Authentication error: %v", err)
		}
	}

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

	gh.client = github.NewClient(tc)
	user, _, _ := gh.client.Users.Get("")
	gh.User.Login = *user.Login
	gh.User.issues = map[string][]*github.Issue{}
	gh.User.Password = ""
	gh.Fetch()
	return nil
}
开发者ID:TechMantra,项目名称:focus,代码行数:34,代码来源:github.go


示例18: 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


示例19: 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


示例20: clientFromToken

func clientFromToken(pat string) *godo.Client {
	tokenSrc := &tokenSource{
		AccessToken: pat,
	}

	return godo.NewClient(oauth2.NewClient(oauth2.NoContext, tokenSrc))
}
开发者ID:franciscod,项目名称:dokernel,代码行数:7,代码来源:client_setup.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang oauth2.ReuseTokenSource函数代码示例发布时间:2022-05-28
下一篇:
Golang websocket.Server类代码示例发布时间: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