在 Cloud Functions (第 1 代) 上运行的由 Storage 触发的函数示例。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
namespace HelloGcs;
/// <summary>
/// Example Cloud Storage-triggered function.
/// This function can process any event from Cloud Storage.
/// </summary>
public class Function : ICloudEventFunction<StorageObjectData>
{
private readonly ILogger _logger;
public Function(ILogger<Function> logger) =>
_logger = logger;
public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken)
{
_logger.LogInformation("Event: {event}", cloudEvent.Id);
_logger.LogInformation("Event Type: {type}", cloudEvent.Type);
_logger.LogInformation("Bucket: {bucket}", data.Bucket);
_logger.LogInformation("File: {file}", data.Name);
_logger.LogInformation("Metageneration: {metageneration}", data.Metageneration);
_logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset());
_logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset());
return Task.CompletedTask;
}
}
Go
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
// Package helloworld provides a set of Cloud Functions samples.
package helloworld
import (
"context"
"fmt"
"log"
"time"
"cloud.google.com/go/functions/metadata"
)
// GCSEvent is the payload of a GCS event.
type GCSEvent struct {
Kind string `json:"kind"`
ID string `json:"id"`
SelfLink string `json:"selfLink"`
Name string `json:"name"`
Bucket string `json:"bucket"`
Generation string `json:"generation"`
Metageneration string `json:"metageneration"`
ContentType string `json:"contentType"`
TimeCreated time.Time `json:"timeCreated"`
Updated time.Time `json:"updated"`
TemporaryHold bool `json:"temporaryHold"`
EventBasedHold bool `json:"eventBasedHold"`
RetentionExpirationTime time.Time `json:"retentionExpirationTime"`
StorageClass string `json:"storageClass"`
TimeStorageClassUpdated time.Time `json:"timeStorageClassUpdated"`
Size string `json:"size"`
MD5Hash string `json:"md5Hash"`
MediaLink string `json:"mediaLink"`
ContentEncoding string `json:"contentEncoding"`
ContentDisposition string `json:"contentDisposition"`
CacheControl string `json:"cacheControl"`
Metadata map[string]interface{} `json:"metadata"`
CRC32C string `json:"crc32c"`
ComponentCount int `json:"componentCount"`
Etag string `json:"etag"`
CustomerEncryption struct {
EncryptionAlgorithm string `json:"encryptionAlgorithm"`
KeySha256 string `json:"keySha256"`
}
KMSKeyName string `json:"kmsKeyName"`
ResourceState string `json:"resourceState"`
}
// HelloGCS consumes a(ny) GCS event.
func HelloGCS(ctx context.Context, e GCSEvent) error {
meta, err := metadata.FromContext(ctx)
if err != nil {
return fmt.Errorf("metadata.FromContext: %w", err)
}
log.Printf("Event ID: %v\n", meta.EventID)
log.Printf("Event type: %v\n", meta.EventType)
log.Printf("Bucket: %v\n", e.Bucket)
log.Printf("File: %v\n", e.Name)
log.Printf("Metageneration: %v\n", e.Metageneration)
log.Printf("Created: %v\n", e.TimeCreated)
log.Printf("Updated: %v\n", e.Updated)
return nil
}
Java
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.GcsEvent;
import java.util.logging.Logger;
/**
* Example Cloud Storage-triggered function.
* This function can process any event from Cloud Storage.
*/
public class HelloGcs implements BackgroundFunction<GcsEvent> {
private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());
@Override
public void accept(GcsEvent event, Context context) {
logger.info("Event: " + context.eventId());
logger.info("Event Type: " + context.eventType());
logger.info("Bucket: " + event.getBucket());
logger.info("File: " + event.getName());
logger.info("Metageneration: " + event.getMetageneration());
logger.info("Created: " + event.getTimeCreated());
logger.info("Updated: " + event.getUpdated());
}
}
Node.js
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
/**
* Generic background Cloud Function to be triggered by Cloud Storage.
* This sample works for all Cloud Storage CRUD operations.
*
* @param {object} file The Cloud Storage file metadata.
* @param {object} context The event metadata.
*/
exports.helloGCS = (file, context) => {
console.log(` Event: ${context.eventId}`);
console.log(` Event Type: ${context.eventType}`);
console.log(` Bucket: ${file.bucket}`);
console.log(` File: ${file.name}`);
console.log(` Metageneration: ${file.metageneration}`);
console.log(` Created: ${file.timeCreated}`);
console.log(` Updated: ${file.updated}`);
};
PHP
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;
// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::cloudEvent('helloGCS', 'helloGCS');
function helloGCS(CloudEventInterface $cloudevent)
{
// This function supports all Cloud Storage event types.
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
$data = $cloudevent->getData();
fwrite($log, 'Event: ' . $cloudevent->getId() . PHP_EOL);
fwrite($log, 'Event Type: ' . $cloudevent->getType() . PHP_EOL);
fwrite($log, 'Bucket: ' . $data['bucket'] . PHP_EOL);
fwrite($log, 'File: ' . $data['name'] . PHP_EOL);
fwrite($log, 'Metageneration: ' . $data['metageneration'] . PHP_EOL);
fwrite($log, 'Created: ' . $data['timeCreated'] . PHP_EOL);
fwrite($log, 'Updated: ' . $data['updated'] . PHP_EOL);
}
Python
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
def hello_gcs(event, context):
"""Background Cloud Function to be triggered by Cloud Storage.
This generic function logs relevant data when a file is changed,
and works for all Cloud Storage CRUD operations.
Args:
event (dict): The dictionary with data specific to this type of event.
The `data` field contains a description of the event in
the Cloud Storage `object` format described here:
https://cloud.google.com/storage/docs/json_api/v1/objects#resource
context (google.cloud.functions.Context): Metadata of triggering event.
Returns:
None; the output is written to Cloud Logging
"""
print(f"Event ID: {context.event_id}")
print(f"Event type: {context.event_type}")
print("Bucket: {}".format(event["bucket"]))
print("File: {}".format(event["name"]))
print("Metageneration: {}".format(event["metageneration"]))
print("Created: {}".format(event["timeCreated"]))
print("Updated: {}".format(event["updated"]))
Ruby
如需向 Cloud Functions 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
require "functions_framework"
FunctionsFramework.cloud_event "hello_gcs" do |event|
# This function supports all Cloud Storage events.
# The `event` parameter is a CloudEvents::Event::V1 object.
# See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
payload = event.data
logger.info "Event: #{event.id}"
logger.info "Event Type: #{event.type}"
logger.info "Bucket: #{payload['bucket']}"
logger.info "File: #{payload['name']}"
logger.info "Metageneration: #{payload['metageneration']}"
logger.info "Created: #{payload['timeCreated']}"
logger.info "Updated: #{payload['updated']}"
end
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。