当前位置: 首页>>代码示例>>Golang>>正文


Golang oauth2.NewClient函数代码示例

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


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


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