Cloud Functions 직접 호출

빠른 반복 및 디버깅을 지원하기 위해 Cloud Functions는 명령줄 인터페이스에서 call 명령어를 제공하며 Google Cloud Console UI에서 테스트 기능을 제공합니다. 이를 통해 함수를 직접 호출하여 예상대로 작동하는지 확인할 수 있습니다. 또한 특정 이벤트에 응답하도록 배포된 함수라도 즉시 실행됩니다.

Google Cloud CLI로 함수 테스트

1세대

gcloud CLI를 사용하여 1세대 함수를 직접 호출하려면 gcloud functions call 명령어를 사용하고 함수에 필요한 데이터를 JSON으로 --data 인수에 제공합니다. 예를 들면 다음과 같습니다.

gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Tristan"}'

여기서 YOUR_FUNCTION_NAME은 실행할 함수 이름입니다. --data 인수는 다음과 같이 함수에 전달됩니다.

  • HTTP 함수의 경우 사용자가 제공한 데이터는 POST 요청 본문으로 전송됩니다.
  • 백그라운드 함수의 경우 데이터는 이벤트 데이터로 함수에 직접 전달됩니다. 백그라운드 함수의 이벤트 데이터에 액세스하는 방법에 대한 자세한 내용은 백그라운드 함수 매개변수를 참조하세요.
  • CloudEvent 함수의 경우 데이터는 이벤트 데이터로 함수에 직접 전달됩니다. CloudEvent 함수의 이벤트 데이터에 액세스하는 방법에 대한 자세한 내용은 CloudEvent 함수 매개변수를 참조하세요.

2세대

gcloud CLI를 사용하여 2세대 함수를 직접 호출하려면 gcloud functions call 명령어의 2세대 버전을 사용하고 함수에 필요한 데이터를 JSON으로 --data 인수에 제공합니다. 예를 들면 다음과 같습니다.

gcloud functions call YOUR_FUNCTION_NAME \
  --region=REGION --gen2 \
  --data '{"name":"Kalani"}'

다음과 같이 바꿉니다.

  • YOUR_FUNCTION_NAME: 테스트할 함수의 이름
  • REGION: 함수가 배포된 Google Cloud 리전

--data 인수는 다음과 같이 함수에 전달됩니다.

  • HTTP 함수의 경우 사용자가 제공한 데이터는 POST 요청 본문으로 전송됩니다.
  • CloudEvent 함수의 경우 데이터는 이벤트 데이터로 함수에 직접 전달됩니다. CloudEvent 함수의 이벤트 데이터에 액세스하는 방법에 대한 자세한 내용은 CloudEvent 함수 매개변수를 참조하세요.

자세한 내용은 gcloud functions call 문서를 참조하세요.

Google Cloud 콘솔에서 함수 테스트

Google Cloud 콘솔에서 직접 함수를 호출하려면 다음 단계를 따르세요.

1세대

  1. Cloud Functions 개요 페이지로 이동

  2. 호출할 함수의 이름을 클릭합니다.

  3. 테스트 중 탭을 클릭합니다.

  4. 트리거 이벤트 구성 필드에 함수에 필요한 데이터를 JSON으로 입력합니다.

  5. 함수 테스트를 클릭합니다.

함수 응답이 출력 필드에 나타나고 개별 실행에 대한 로그가 로그 필드에 나타납니다.

2세대

  1. Cloud Functions 개요 페이지로 이동

  2. 목록에서 호출할 함수 이름을 클릭합니다. 그러면 함수 세부정보 페이지로 이동합니다.

  3. 테스트 중 탭을 클릭합니다.

  4. 트리거 이벤트 구성 필드에 함수에 필요한 데이터를 JSON으로 입력합니다.

  5. +쿼리 매개변수 추가+헤더 매개변수 추가 버튼을 클릭하여 필요에 따라 쿼리 및 헤더 매개변수를 함수 호출에 추가합니다.

    Google Cloud 콘솔은 지정된 매개변수를 CLI 테스트 명령어 창의 gcloud functions call 명령어로 조합합니다.

  6. Cloud Shell에서 실행을 선택하여 이 명령어를 실행할 Cloud Shell 창을 엽니다.

  7. Cloud Shell 창에 표시된 gcloud functions call 명령어를 트리거하려면 Enter 키를 누릅니다.

Cloud Pub/Sub 이벤트 기반 함수 예시

이 예시에서는 Cloud Pub/Sub 이벤트에서 트리거한 1세대 이벤트 기반 함수를 직접 호출하는 방법을 보여줍니다.

Node.js

/**
 * 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 = message.data
    ? Buffer.from(message.data, 'base64').toString()
    : 'World';

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

Python

def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
                        event. The `@type` field maps to
                         `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                        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 (google.cloud.functions.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
                        pubsub.googleapis.com, the triggering topic's name, and
                        the triggering event type
                        `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
    Returns:
        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")
    else:
        name = "World"
    print(f"Hello {name}!")

Go


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

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
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
}

Java


import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
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());

  @Override
  public void accept(PubsubMessage message, Context context) {
    String name = "world";
    if (message != null && message.getData() != null) {
      name = new String(
          Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
          StandardCharsets.UTF_8);
    }
    logger.info(String.format("Hello %s!", name));
    return;
  }
}

C#

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;
    }
}

Ruby

require "functions_framework"
require "base64"

FunctionsFramework.cloud_event "hello_pubsub" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  name = Base64.decode64 event.data["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.
  logger.info "Hello, #{name}!"
end

PHP


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);
}

함수를 직접 호출하려면 base64로 인코딩된 데이터가 필요한 PubsubMessage를 이벤트 데이터로 보냅니다.

Node.js

DATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{"data":"'$DATA'"}'

Python

DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'

Go

DATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{"data":"'$DATA'"}'

Java

DATA=$(printf 'Hello!'|base64) && gcloud functions call java-hello-pubsub --data '{"data":"'$DATA'"}'

C#

DATA=$(printf 'Hello!'|base64) && gcloud functions call csharp-hello-pubsub --data '{"data":"'$DATA'"}'

Ruby

DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'

PHP

DATA=$(printf 'Hello!'|base64) && gcloud functions call helloworldPubsub --data '{"data":"'$DATA'"}'

이 CLI 예시에서는 bash 또는 sh 구문을 사용합니다. Linux 및 Mac 환경에서 작동하지만 Windows에서는 작동하지 않습니다.

트리거 이벤트 필드에서 같은 이벤트 데이터를 사용하여 Google Cloud 콘솔에서 함수를 호출할 수도 있습니다.