本文整理汇总了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)
}
示例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
}
示例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)
}
示例4: GetOauthClient
func GetOauthClient(token string) *http.Client {
tokenSource := &TokenSource{
AccessToken: token,
}
return oauth2.NewClient(oauth2.NoContext, tokenSource)
}
示例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)
}
示例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
},
}
}
}
}
示例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)
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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")))
}