百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

gcpsamples

> 数据库
开源

用于在 (node,dotnet,java,golang,Python) 中访问 Google Cloud API 的简单"Hello world"示例

99 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于在 (node,dotnet,java,golang,Python) 中访问 Google Cloud API 的简单"Hello world"示例

Google Cloud Platform API hello world samples

samples provided as-is without warranty

Sample code demonstrating various Auth mechanism for Google Cloud Platform APIs.

Please refer to official documentation for usage and additional samples/usage.

Google Authentication Samples


Application Default Credentials

The samples use Application Default Credentials which uses credentials in the following order as described in the link. Set the environment variable to override.

You can always specify the target source to acquire credentials by using intent specific targets such as: ComputeCredentials, UserCredentials or ServiceAccountCredential.

There are two types of client libraries you can use to connect to Google APIs:

  • Google Cloud Client Libraries
  • Gooogle API Client Libraries ' + str(p.end_time) + ' : [' + str(p.value.get('bucketCounts')) + ']') print('-----------------')

##### Using google.auth for GoogleAPIs

The following shows transport authorization for the original Google APIs

```python
import oauth2client
from oauth2client.client import GoogleCredentials
import httplib2

http = httplib2.Http()
credentials = GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
  credentials = credentials.create_scoped(scopes)
http = credentials.authorize(http)

If you need to use the more recent Google Cloud Auth library, you need to cast the transport:

  • http://google-auth.readthedocs.io/en/latest/reference/google.auth.html
  • https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2
python
import google.auth
import google_auth_httplib2

scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials, project = google.auth.default(scopes=scopes)
http =  google_auth_httplib2.AuthorizedHttp(credentials)

or preferably init a cloud API:

python
from google.cloud import storage
import google.auth
from google.oauth2 import service_account
import os

#credentials = service_account.Credentials.from_service_account_file('YOUR_JSON_CERT.json')
#if credentials.requires_scopes:
#  credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_write'])
#client = storage.Client(credentials=credentials)

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/svc_account.json"
credentials, project = google.auth.default()    
client = storage.Client(credentials=credentials)
buckets = client.list_buckets()
for bkt in buckets:
  print(bkt)
Logging_Cloud_python

If you want to enable trace logging with google-cloud-python* library set,

python
#!/usr/bin/python

from google.cloud import bigquery
from six.moves import http_client

http_client.HTTPConnection.debuglevel = 5

client = bigquery.Client()
query_job = client.query("""
        SELECT timestamp
FROM
 `your-project.gae_request_logs.appengine_googleapis_com_request_log_20161119`
ORDER BY timestamp DESC
LIMIT
 4;""")

results = query_job.result()
for row in results:
        print(row)

…

xml
  
      com.google.cloud
      google-cloud-storage
      zzzz
  

  
    com.google.cloud
    google-cloud-pubsub
    yyyy
  
java
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Blob.BlobSourceOption;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;

import com.google.cloud.storage.Storage.SignUrlOption;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import java.util.Iterator;
import java.io.FileInputStream;

//import com.google.auth.oauth2.ServiceAccountCredentials;

// Using Google Cloud APIs with service account file
// You can also just export an export GOOGLE_APPLICATION_CREDENTIALS and use StorageOptions.defaultInstance().service()
// see https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http
/*
Storage storage_service = StorageOptions.newBuilder()
			.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("/path/to/your/certificate.json")))
			.build()
			.getService();			
*/

Storage storage_service = StorageOptions.newBuilder()
	.build()
	.getService();
for (Bucket b : storage_service.list().iterateAll()){
  System.out.println(b);
}

// You can also use the client to generate a signed URL:
URL signedUrl = storage_service.signUrl(BlobInfo.newBuilder("your_project", "a.txt").build(), 60,  TimeUnit.SECONDS);
System.out.println(signedUrl);
Proxy Server Settings

see proxy/README.md

Async Futures

see Example

java

import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.Binding;
import com.google.cloud.Role;

    // setup topicadmin client using the bit above
	TopicAdminClient topicClient =
	  TopicAdminClient.create(
		  TopicAdminSettings.newBuilder()
			  .setTransportChannelProvider(channelProvider)
			  .setCredentialsProvider(credentialsProvider)
              .build());

      String formattedResource = TopicName.create("your-project", "saltopic2").toString();

      GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()
        .setResource(formattedResource)
        .build();
      ApiFuture future = topicAdminClient.getIamPolicyCallable().futureCall(request);
      Policy response = future.get();
      System.out.println(response);

Cloud Go

Package cloud.google.com/go/storage

  • https://github.com/GoogleCloudPlatform/google-cloud-go
  • https://godoc.org/google.golang.org/api/storage/v1

The following shows google.DefaultTokenSource as well as gcloud's Application Default Credentials

go
import (
        "golang.org/x/net/context"
        "cloud.google.com/go/storage"
        "google.golang.org/api/iterator"
        "google.golang.org/api/option"
        "log"  
)

	ctx := context.Background()
	/*
		tokenSource, err := google.DefaultTokenSource(oauth2.NoContext, storage.ScopeReadOnly)
		if err != nil {
			log.Fatalf("Unable to acquire token source: %v", err)
		}
		storeageClient, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))
	*/

	storeageClient, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatalf("Unable to acquire storage Client: %v", err)
	}

	it := storeageClient.Buckets(ctx, "your_project")
	for {
		bucketAttrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("Unable to acquire storage Client: %v", err)
		}
		log.Printf(bucketAttrs.Name)
	}
Adding custom headers
go
package main

import (
  "context"
  "io/ioutil"
  "log"
  "net/http"

  "cloud.google.com/go/storage"
  "google.golang.org/api/option"
  raw "google.golang.org/api/storage/v1"
  htransport "google.golang.org/api/transport/http"
)

func main() {

  ctx := context.Background()

  // Standard way to initialize client:
  // client, err := storage.NewClient(ctx)
  // if err != nil {
  //      // handle error
  // }

  // Instead, create a custom http.Client.
  base := http.DefaultTransport
  trans, err := htransport.NewTransport(ctx, base, option.WithScopes(raw.DevstorageFullControlScope),
            option.WithUserAgent("custom-user-agent"))
  if err != nil {
            // Handle error.
  }
  c := http.Client{Transport:trans}

  // Add RoundTripper to the created HTTP client.
  c.Transport = withDebugHeader{c.Transport}

  // Supply this client to storage.NewClient
  client, err := storage.NewClient(ctx, option.WithHTTPClient(&c))
  if err != nil {
              // Handle error.
  }

  // Use client...
 }

type withDebugHeader struct {
  rt http.RoundTripper
}

func (wdh withDebugHeader) RoundTrip(r *http.Request) (*http.Response, error) {
  headerName := "X-Custom-Header"
  r.Header.Add(headerName, "value")
  resp, err := wdh.rt.RoundTrip(r)
  if err == nil {
    log.Printf("Resp Header: %+v, ", resp.Header.Get(headerName))
  } else {
    log.Printf("Error: %+v", err)
  }
  return resp, err
}

…

node
const Storage = require('@google-cloud/storage');
const storage = new Storage({
    projectId: 'your-project',
  });

storage.getBuckets(function(err, buckets) {
  if (!err) {
  	buckets.forEach(function(value){
  			logger.info(value.id);
	});
  }
});

const Pubsub = require('@google-cloud/pubsub');
const pubsub = Pubsub({
    projectId: 'your-project'
  });
  pubsub.getTopics((err, topic) => {
      if (err) {
          logger.error(err);
          return;
      }
      topic.forEach(function(entry) {
      logger.info(entry.name);
      });
  });

Cloud C#

Use Google.Cloud.Storage.V1 package for Google Cloud API access

  • google-cloud-dotnet
  • API Documentation

See auth/service/dotnet for sample for both Cloud APIs and Google APIs libraries.

csharp
using Google.Cloud.Storage.V1;

namespace CloudStorageAppGcloud
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = StorageClient.Create();

            foreach (var obj in client.ListObjects("your_project", ""))
            {
                Console.WriteLine(obj.Name);
            }
            Console.ReadLine();
        }
    }
}

gRPC Environment Variables

  • https://github.com/grpc/grpc/blob/master/doc/environment_variables.md

JWT Access Token

    • auth/service/jwt_access_token

JWT access tokens are efficient way to access certain google apis without the extra round trip to get an access_token. Unlike the normal Oauth service account flow where you

  1. use a local service account to sign a JWT,
  2. Exchange that JWT with google to get an access_token
  3. Use that access_token to make an API call to google

with JWT Access Tokens, all you do is sign a JWT locally with a service account with the intended Service you want to access and then simply send it to the service.

The following links describes this flow:

  • JWT Auth

where these Google APIs will support this:

  • https://github.com/googleapis/googleapis/tree/master/google

eg. for PubSub

go
	// https://github.com/googleapis/googleapis/blob/master/google/pubsub/pubsub.yaml#L6

	ctx := context.Background()
	projectID := "YOUR_PROJECT"
	keyfile := "service_account.json"

	audience := "https://pubsub.googleapis.com/google.pubsub.v1.Publisher"

	keyBytes, err := ioutil.ReadFile(keyfile)
	if err != nil {
		log.Fatalf("Unable to read service account key file  %v", err)
	}
	tokenSource, err := google.JWTAccessTokenSourceFromJSON(keyBytes, audience)
	if err != nil {
		log.Fatalf("Error building JWT access token source: %v", err)
	}
	jwt, err := tokenSource.Token()
	if err != nil {
		log.Fatalf("Unable to generate JWT token: %v", err)
	}
	fmt.Println(jwt.AccessToken)

	pubsubClient, err := pubsub.NewClient(ctx, projectID, option.WithTokenSource(token

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Gocloud-apicloud-clientgoogle-cloudgoogle-cloud-platform

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库