1 | initial version |
To send a pubsub message when a cloud function with HTTP trigger is activated by someone, you can use the Cloud Pub/Sub client library and the pubsub topic webhook.
Here are the steps:
Create a Cloud Pub/Sub topic and add a subscriber to it. The subscriber can be a Cloud Function that will receive the message.
In your Cloud Function code, import the Pub/Sub client library and configure it to use the appropriate credentials.
In your function code, use the Pub/Sub client library to publish a message to the topic.
In your Pub/Sub subscriber function code, read the message and perform any necessary actions.
Here's an example code snippet that sends a Pub/Sub message when an HTTP Cloud Function is triggered:
import base64
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
topic_name = 'projects/{project_id}/topics/{topic_name}'.format(
project_id='<your-project-id>',
topic_name='<your-topic-name>',
)
def my_function(request):
# Do something
# ...
# Publish a message to Pub/Sub
message = 'Hello, world!'
message_bytes = message.encode('utf-8')
message = base64.b64encode(message_bytes).decode('utf-8')
publisher.publish(topic_name, data=message)
return 'Message published to Pub/Sub.'
When this function is triggered by an HTTP request, it will publish a 'Hello, world!' message to the given Pub/Sub topic. The subscriber function can then read this message and perform any necessary actions.