이 가이드에서는 gcloud functions 명령어를 사용하여 소스 코드에서 함수를 로컬로 호출하는 방법을 보여줍니다. 함수 프레임워크를 사용하여 Cloud Run Functions를 로컬에서 개발하고 테스트하는 방법을 알아보려면 로컬 함수 개발을 참조하세요.
Cloud Functions v2 API로 만든 함수의 빠른 반복 및 디버깅을 지원하기 위해 명령줄 인터페이스에서 call 명령어를 사용할 수 있습니다. 이를 통해 함수를 직접 호출하여 예상대로 작동하는지 확인할 수 있습니다. 또한 특정 이벤트에 응답하도록 배포된 함수라도 즉시 실행됩니다.
Google Cloud CLI로 함수 테스트
gcloud CLI를 사용하여 함수를 직접 호출하려면 gcloud functions call 명령어를 사용하고 함수에 필요한 데이터를 --data 인수에 JSON으로 제공합니다. 예를 들면 다음과 같습니다.
다음 예시에서는 Pub/Sub 이벤트에 의해 트리거된 이벤트 기반 함수를 직접 호출하는 방법을 보여줍니다.
Node.js
constfunctions=require('@google-cloud/functions-framework');// Register a CloudEvent callback with the Functions Framework that will// be executed when the Pub/Sub trigger topic receives a message.functions.cloudEvent('helloPubSub',cloudEvent=>{// The Pub/Sub message is passed as the CloudEvent's data payload.constbase64name=cloudEvent.data.message.data;constname=base64name?Buffer.from(base64name,'base64').toString():'World';console.log(`Hello, ${name}!`);});
Python
importbase64fromcloudevents.httpimportCloudEventimportfunctions_framework# Triggered from a message on a Cloud Pub/Sub topic.@functions_framework.cloud_eventdefsubscribe(cloud_event:CloudEvent)-> None:# Print out the data from Pub/Sub, to prove that it workedprint("Hello, "+base64.b64decode(cloud_event.data["message"]["data"]).decode()+"!")
Go
// Package helloworld provides a set of Cloud Functions samples.packagehelloworldimport("context""fmt""log""github.com/GoogleCloudPlatform/functions-framework-go/functions""github.com/cloudevents/sdk-go/v2/event")funcinit(){functions.CloudEvent("HelloPubSub",helloPubSub)}// MessagePublishedData contains the full Pub/Sub message// See the documentation for more details:// https://cloud.google.com/eventarc/docs/cloudevents#pubsubtypeMessagePublishedDatastruct{MessagePubSubMessage}// PubSubMessage is the payload of a Pub/Sub event.// See the documentation for more details:// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessagetypePubSubMessagestruct{Data[]byte`json:"data"`}// helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.funchelloPubSub(ctxcontext.Context,eevent.Event)error{varmsgMessagePublishedDataiferr:=e.DataAs(&msg);err!=nil{returnfmt.Errorf("event.DataAs: %w",err)}name:=string(msg.Message.Data)// Automatically decoded from base64.ifname==""{name="World"}log.Printf("Hello, %s!",name)returnnil}
자바
importcom.google.cloud.functions.CloudEventsFunction;importcom.google.gson.Gson;importfunctions.eventpojos.PubSubBody;importio.cloudevents.CloudEvent;importjava.nio.charset.StandardCharsets;importjava.util.Base64;importjava.util.logging.Logger;publicclassSubscribeToTopicimplementsCloudEventsFunction{privatestaticfinalLoggerlogger=Logger.getLogger(SubscribeToTopic.class.getName());@Overridepublicvoidaccept(CloudEventevent){// The Pub/Sub message is passed as the CloudEvent's data payload.if(event.getData()!=null){// Extract Cloud Event data and convert to PubSubBodyStringcloudEventData=newString(event.getData().toBytes(),StandardCharsets.UTF_8);Gsongson=newGson();PubSubBodybody=gson.fromJson(cloudEventData,PubSubBody.class);// Retrieve and decode PubSub message dataStringencodedData=body.getMessage().getData();StringdecodedData=newString(Base64.getDecoder().decode(encodedData),StandardCharsets.UTF_8);logger.info("Hello, "+decodedData+"!");}}}
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.htmlname=Base64.decode64event.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를 이벤트 데이터로 보냅니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-22(UTC)"],[[["\u003cp\u003eCloud Functions v2 API allows direct invocation of functions using the \u003ccode\u003egcloud functions call\u003c/code\u003e command for testing and debugging purposes.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egcloud functions call\u003c/code\u003e command requires providing function-specific data as JSON within the \u003ccode\u003e--data\u003c/code\u003e argument.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003e--data\u003c/code\u003e argument's content is sent as the body of a POST request for HTTP functions and as the event data for CloudEvent functions.\u003c/p\u003e\n"],["\u003cp\u003eDirect function invocations are designed for testing, not production, and utilize a \u003ccode\u003ecall\u003c/code\u003e method with a limited, non-expandable quota.\u003c/p\u003e\n"],["\u003cp\u003eThe document gives examples of direct invocations for various programming languages such as Node.js, Python, Go, Java, C#, Ruby, and PHP.\u003c/p\u003e\n"]]],[],null,[]]