Ask Your Question
0

How can I send a pubsub message when a cloud function with http trigger is activated by someone?

asked 2021-09-25 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-05 22:00:00 +0000

woof gravatar image

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:

  1. Create a Cloud Pub/Sub topic and add a subscriber to it. The subscriber can be a Cloud Function that will receive the message.

  2. In your Cloud Function code, import the Pub/Sub client library and configure it to use the appropriate credentials.

  3. In your function code, use the Pub/Sub client library to publish a message to the topic.

  4. 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-25 11:00:00 +0000

Seen: 9 times

Last updated: Mar 05 '23