當前位置: 首頁>>代碼示例>>Golang>>正文


Golang google.DefaultClient函數代碼示例

本文整理匯總了Golang中golang.org/x/oauth2/google.DefaultClient函數的典型用法代碼示例。如果您正苦於以下問題:Golang DefaultClient函數的具體用法?Golang DefaultClient怎麽用?Golang DefaultClient使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了DefaultClient函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: newComputeUtil

// NewComputeUtil creates and initializes a ComputeUtil.
func newComputeUtil(driver *Driver) (*ComputeUtil, error) {
	client, err := google.DefaultClient(oauth2.NoContext, raw.ComputeScope)
	if err != nil {
		return nil, err
	}

	service, err := raw.New(client)
	if err != nil {
		return nil, err
	}

	return &ComputeUtil{
		zone:              driver.Zone,
		instanceName:      driver.MachineName,
		userName:          driver.SSHUser,
		project:           driver.Project,
		diskTypeURL:       driver.DiskType,
		address:           driver.Address,
		network:           driver.Network,
		preemptible:       driver.Preemptible,
		useInternalIP:     driver.UseInternalIP,
		useInternalIPOnly: driver.UseInternalIPOnly,
		service:           service,
		zoneURL:           apiURL + driver.Project + "/zones/" + driver.Zone,
		globalURL:         apiURL + driver.Project + "/global",
		SwarmMaster:       driver.SwarmMaster,
		SwarmHost:         driver.SwarmHost,
	}, nil
}
開發者ID:bgokden,項目名稱:machine,代碼行數:30,代碼來源:compute_util.go

示例2: pubsubContext

func pubsubContext(ctx context.Context, projectID string) (context.Context, error) {
	httpClient, err := google.DefaultClient(ctx, pubsub.ScopePubSub)
	if err != nil {
		return nil, err
	}
	return cloud.WithContext(ctx, projectID, httpClient), nil
}
開發者ID:wuman,項目名稱:golang-samples,代碼行數:7,代碼來源:pubsub.go

示例3: GetService

func GetService() (*deploymentmanager.Service, error) {
	client, err := google.DefaultClient(oauth2.NoContext, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return &deploymentmanager.Service{}, err
	}
	return deploymentmanager.New(client)
}
開發者ID:evandbrown,項目名稱:dm,代碼行數:7,代碼來源:deployment.go

示例4: GetStorageService

func GetStorageService(ctx context.Context) (*storage.Service, error) {
	client, err := google.DefaultClient(ctx, storage.DevstorageFullControlScope)
	if err != nil {
		return nil, err
	}
	return storage.New(client)
}
開發者ID:xanxys,項目名稱:bonsai,代碼行數:7,代碼來源:main.go

示例5: handler

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	search, allele, err := requestToSearch(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	client, err := google.DefaultClient(c, genomics.GenomicsReadonlyScope)
	if err != nil {
		http.Error(w, "Invalid server configuration", http.StatusInternalServerError)
	}
	genomicsService, err := genomics.New(client)
	if err != nil {
		http.Error(w, "Invalid server configuration", http.StatusInternalServerError)
	}
	variantsService := genomics.NewVariantsService(genomicsService)

	type beaconResponse struct {
		XMLName struct{} `xml:"BEACONResponse"`
		Exists  bool     `xml:"exists"`
	}
	var resp beaconResponse

	for {
		searchResponse, err := variantsService.Search(search).Do()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for _, variant := range searchResponse.Variants {
			if search.Start != variant.Start {
				continue
			}
			if allele == variant.ReferenceBases {
				resp.Exists = true
			} else {
				for _, base := range variant.AlternateBases {
					if base == allele {
						resp.Exists = true
						break
					}
				}
			}
		}

		if resp.Exists || searchResponse.NextPageToken == "" {
			break
		}
		search.PageToken = searchResponse.NextPageToken
	}

	w.Header().Set("Content-Type", "application/xml")
	enc := xml.NewEncoder(w)
	enc.Indent("", "  ")
	if err = enc.Encode(resp); err != nil {
		http.Error(w, "Failed writing response", http.StatusInternalServerError)
	}
}
開發者ID:googlegenomics,項目名稱:beacon-go,代碼行數:60,代碼來源:beacon.go

示例6: ListBuckets

// ListBuckets returns a slice of all the buckets in the given projectId.
// [START ListBuckets]
func ListBuckets(projectId string) ([]*storage.Bucket, error) {
	// Create the client that uses Application Default Credentials
	client, err := google.DefaultClient(
		oauth2.NoContext,
		"https://www.googleapis.com/auth/devstorage.read_only")
	if err != nil {
		return nil, err
	}

	// Create the Google Cloud Storage service
	service, err := storage.New(client)
	if err != nil {
		return nil, err
	}

	// Create the request to list buckets for the project id
	request := service.Buckets.List(projectId)

	// Execute the request
	buckets, err := request.Do()
	if err != nil {
		return nil, err
	}

	return buckets.Items, nil
}
開發者ID:dwightjl,項目名稱:go-docs-samples,代碼行數:28,代碼來源:listbuckets.go

示例7: datasets

// datasets returns a list with the IDs of all the Big Query datasets visible
// with the given context.
func datasets(ctx context.Context) ([]string, error) {
	// Create a new authenticated HTTP client over urlfetch.
	hc, err := google.DefaultClient(ctx, bigquery.BigqueryScope)
	if err != nil {
		return nil, fmt.Errorf("could not create http client: %v", err)
	}

	// Create the BigQuery service.
	bq, err := bigquery.New(hc)
	if err != nil {
		return nil, fmt.Errorf("could not create service: %v", err)
	}

	// Get the current application ID, which is the same as the project ID.
	projectID := appengine.AppID(ctx)

	// Return a list of IDs.
	var ids []string
	datasets, err := bq.Datasets.List(projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("could not list datasets for %q: %v", projectID, err)
	}
	for _, d := range datasets.Datasets {
		ids = append(ids, d.Id)
	}
	return ids, nil
}
開發者ID:GoogleCloudPlatform,項目名稱:golang-samples,代碼行數:29,代碼來源:app.go

示例8: handleStoragePut

func handleStoragePut(c context.Context, w http.ResponseWriter, r *http.Request) {
	bucket := r.URL.Query().Get("bucket")
	name := r.URL.Query().Get("name")
	value := r.URL.Query().Get("value")
	if bucket == "" || name == "" || value == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("Missing bucket, name, or value query parameter."))
		return
	}
	client, err := google.DefaultClient(c, storage.DevstorageReadWriteScope)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to get default google client. " + err.Error()))
		return
	}
	service, err := storage.New(client)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to get storage service. " + err.Error()))
		return
	}
	obj, err := service.Objects.Insert(bucket, &storage.Object{Name: name}).Media(strings.NewReader(value)).Do()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to insert object. " + err.Error()))
		return
	}
	w.Write([]byte(fmt.Sprintf("put succeeded: %v", obj)))
}
開發者ID:drichardson,項目名稱:go-appengine-vm-example,代碼行數:29,代碼來源:app.go

示例9: Publish

func (f *Fetcher) Publish(request *FetchRequest, entries []*FetchResponse) (err error) {
	client, err := google.DefaultClient(request.Context, pubsub.CloudPlatformScope)
	if err != nil {
		return
	}
	service, err := pubsub.New(client)
	if err != nil {
		return
	}
	messages := make([]*pubsub.PubsubMessage, len(entries))
	for i := range entries {
		messages[i] = &pubsub.PubsubMessage{
			Data: base64.StdEncoding.EncodeToString(entries[i].Content),
		}
	}
	pr := pubsub.PublishRequest{
		Messages: messages,
	}
	var topic string
	if request.Topic != "" {
		topic = request.Topic
	} else {
		topic = f.Topic
	}
	if topic == "" {
		return fmt.Errorf("fetcher: topic is empty")
	}

	full := fmt.Sprintf("projects/%s/topics/%s", request.AppID(), topic)
	_, err = service.Projects.Topics.Publish(full, &pr).Do()
	if err != nil {
		return
	}
	return
}
開發者ID:pombredanne,項目名稱:appengine-toolkit,代碼行數:35,代碼來源:fetcher.go

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

示例11: init

func init() {
	if !metadata.OnGCE() {
		return
	}
	hc, err := google.DefaultClient(oauth2.NoContext)
	if err != nil {
		registerBrokenFS(fmt.Errorf("could not get http client for context: %v", err))
		return
	}
	projID, err := metadata.ProjectID()
	if projID == "" || err != nil {
		registerBrokenFS(fmt.Errorf("could not get GCE project ID: %v", err))
		return
	}
	ctx := cloud.NewContext(projID, hc)
	sc, err := storage.NewClient(ctx)
	if err != nil {
		registerBrokenFS(fmt.Errorf("could not get cloud storage client: %v", err))
		return
	}
	wkfs.RegisterFS("/gcs/", &gcsFS{
		ctx: ctx,
		sc:  sc,
	})
}
開發者ID:cgag,項目名稱:coreos-baremetal,代碼行數:25,代碼來源:gcs.go

示例12: authenticatedClient

// If we're not running on GCE (e.g. dev mode on localhost) and have
// no other way to get the info, the error value is is errNoRefresh.
func (h *DeployHandler) authenticatedClient() (project string, hc *http.Client, err error) {
	project = os.Getenv("CAMLI_GCE_PROJECT")
	accountFile := os.Getenv("CAMLI_GCE_SERVICE_ACCOUNT")
	if project != "" && accountFile != "" {
		data, errr := ioutil.ReadFile(accountFile)
		err = errr
		if err != nil {
			return
		}
		jwtConf, errr := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/compute.readonly")
		err = errr
		if err != nil {
			return
		}
		hc = jwtConf.Client(context.Background())
		return
	}
	if !metadata.OnGCE() {
		err = errNoRefresh
		return
	}
	project, _ = metadata.ProjectID()
	hc, err = google.DefaultClient(oauth2.NoContext)
	return project, hc, err
}
開發者ID:preillyme,項目名稱:camlistore,代碼行數:27,代碼來源:handler.go

示例13: getComputeClient

func getComputeClient() (*compute.Service, error) {
	const retries = 10
	const backoff = time.Second * 6

	// Setup the gce client for provisioning instances
	// Getting credentials on gce jenkins is flaky, so try a couple times
	var err error
	var cs *compute.Service
	for i := 0; i < retries; i++ {
		if i > 0 {
			time.Sleep(backoff)
		}

		var client *http.Client
		client, err = google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
		if err != nil {
			continue
		}

		cs, err = compute.New(client)
		if err != nil {
			continue
		}
		return cs, nil
	}
	return nil, err
}
開發者ID:ncdc,項目名稱:kubernetes,代碼行數:27,代碼來源:run_remote.go

示例14: handleStorageGet

func handleStorageGet(c context.Context, w http.ResponseWriter, r *http.Request) {
	bucket := r.URL.Query().Get("bucket")
	name := r.URL.Query().Get("name")
	if bucket == "" || name == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("Missing bucket or name query parameter."))
		return
	}
	client, err := google.DefaultClient(c, storage.DevstorageReadOnlyScope)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to get default google client. " + err.Error()))
		return
	}
	service, err := storage.New(client)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to get storage service. " + err.Error()))
		return
	}
	res, err := service.Objects.Get(bucket, name).Download()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed to get object. " + err.Error()))
		return
	}
	w.Header().Set("Content-Type", res.Header.Get("Content-Type"))
	_, err = io.Copy(w, res.Body)
	if err != nil {
		// to late to change status code now
		clog.Errorf(c, "io.Copy failed to copy storage get to response. %v", err)
	}
}
開發者ID:drichardson,項目名稱:go-appengine-vm-example,代碼行數:33,代碼來源:app.go

示例15: init

func init() {
	var err error
	cloudClient, err = google.DefaultClient(context.Background())
	if err != nil {
		panic(err)
	}
}
開發者ID:flowlo,項目名稱:coduno-api,代碼行數:7,代碼來源:cloud.go


注:本文中的golang.org/x/oauth2/google.DefaultClient函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。