Cloud Storage Hello World

Storage の 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
    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;


#include <google/cloud/functions/cloud_event.h>
#include <boost/log/trivial.hpp>
#include <nlohmann/json.hpp>

namespace gcf = ::google::cloud::functions;

void hello_world_storage(gcf::CloudEvent event) {  // NOLINT
  if (event.data_content_type().value_or("") != "application/json") {
    BOOST_LOG_TRIVIAL(error) << "expected application/json data";
  auto const payload = nlohmann::json::parse("{}"));
  BOOST_LOG_TRIVIAL(info) << "Event: " <<;
  BOOST_LOG_TRIVIAL(info) << "Event Type: " << event.type();
  BOOST_LOG_TRIVIAL(info) << "Bucket: " << payload.value("bucket", "");
  BOOST_LOG_TRIVIAL(info) << "Object: " << payload.value("name", "");
  BOOST_LOG_TRIVIAL(info) << "Metageneration: "
                          << payload.value("metageneration", "");
  BOOST_LOG_TRIVIAL(info) << "Created: " << payload.value("timeCreated", "");
  BOOST_LOG_TRIVIAL(info) << "Updated: " << payload.value("updated", "");


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (


// 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 GCS event.
func HelloGCS(ctx context.Context, e GCSEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %v", 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


import functions.eventpojos.GcsEvent;
import java.util.logging.Logger;

public class HelloGcs implements BackgroundFunction<GcsEvent> {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  public void accept(GcsEvent event, Context context) {"Event: " + context.eventId());"Event Type: " + context.eventType());"Bucket: " + event.getBucket());"File: " + event.getName());"Metageneration: " + event.getMetageneration());"Created: " + event.getTimeCreated());"Updated: " + event.getUpdated());


 * Generic background Cloud Function to be triggered by Cloud Storage.
 * @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: ${}`);
  console.log(`  Metageneration: ${file.metageneration}`);
  console.log(`  Created: ${file.timeCreated}`);
  console.log(`  Updated: ${file.updated}`);


use Google\CloudFunctions\CloudEvent;

function helloGCS(CloudEvent $cloudevent)
    $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);


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.

        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:
        context ( Metadata of triggering event.
        None; the output is written to Stackdriver Logging

    print('Event ID: {}'.format(context.event_id))
    print('Event type: {}'.format(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']))


require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See
  payload = "Event: #{}" "Event Type: #{event.type}" "Bucket: #{payload['bucket']}" "File: #{payload['name']}" "Metageneration: #{payload['metageneration']}" "Created: #{payload['timeCreated']}" "Updated: #{payload['updated']}"


他の Google Cloud プロダクトに関連するコードサンプルの検索および条件付き検索を行うには、Google Cloud のサンプルをご覧ください。