Cloud Functions(1세대): Pub/Sub Hello World

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

Cloud Functions(1세대)에서 실행되는 Pub/Sub 트리거 함수 예시

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플


using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloPubSub
    public class Function : ICloudEventFunction<MessagePublishedData>
        private readonly ILogger _logger;

        public Function(ILogger<Function> logger) =>
            _logger = logger;

        public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
            string nameFromMessage = data.Message?.TextData;
            string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
            _logger.LogInformation("Hello {name}", name);
            return Task.CompletedTask;


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

import (

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
type PubSubMessage struct {
	Data []byte `json:"data"`

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
	name := string(m.Data) // Automatically decoded from base64.
	if name == "" {
		name = "World"
	log.Printf("Hello, %s!", name)
	return nil


import functions.eventpojos.PubsubMessage;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

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

  public void accept(PubsubMessage message, Context context) {
    String name = "world";
    if (message != null && message.getData() != null) {
      name = new String(
    }"Hello %s!", name));


import functions.eventpojos.PubsubMessage
import java.nio.charset.StandardCharsets
import java.util.Base64
import java.util.logging.Logger

class KotlinHelloPubSub : BackgroundFunction<PubsubMessage> {
    override fun accept(message: PubsubMessage, context: Context) {
        // name's default value is "world"
        var name = "world"
        if (message?.data != null) {
            name = String(
        }"Hello %s!", name))

    companion object {
        private val LOGGER = Logger.getLogger(


 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 * @param {object} message The Pub/Sub message.
 * @param {object} context The event metadata.
exports.helloPubSub = (message, context) => {
  const name =
    ? Buffer.from(, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);


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('helloworldPubsub', 'helloworldPubsub');

function helloworldPubsub(CloudEventInterface $event): void
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $cloudEventData = $event->getData();
    $pubSubData = base64_decode($cloudEventData['message']['data']);

    $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';
    fwrite($log, "Hello, $name!" . PHP_EOL);


def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
         event (dict):  The dictionary with data specific to this type of
                        event. The `@type` field maps to
                        The `data` field maps to the PubsubMessage data
                        in a base64-encoded string. The `attributes` field maps
                        to the PubsubMessage attributes if any is present.
         context ( Metadata of triggering event
                        including `event_id` which maps to the PubsubMessage
                        messageId, `timestamp` which maps to the PubsubMessage
                        publishTime, `event_type` which maps to
                        `google.pubsub.topic.publish`, and `resource` which is
                        a dictionary that describes the service API endpoint
              , the triggering topic's name, and
                        the triggering event type
        None. The output is written to Cloud Logging.
    import base64

    print("""This Function was triggered by messageId {} published at {} to {}
    """.format(context.event_id, context.timestamp, context.resource["name"]))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
        name = 'World'
    print('Hello {}!'.format(name))


require "functions_framework"
require "base64"

FunctionsFramework.cloud_event "hello_pubsub" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See
  name = Base64.decode64["message"]["data"] rescue "World"

  # A cloud_event function does not return a response, but you can log messages
  # or cause side effects such as sending additional events. "Hello, #{name}!"

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.