Handler for Pub/Sub messages
Stay organized with collections
Save and categorize content based on your preferences.
Service to handle messages delivered by a Cloud Pub/Sub Push subscription.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[],[],null,["# Handler for Pub/Sub messages\n\nService to handle messages delivered by a Cloud Pub/Sub Push subscription.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Use Pub/Sub with Cloud Run tutorial](/run/docs/tutorials/pubsub)\n- [Using Pub/Sub with Knative serving](/anthos/run/archive/docs/tutorials/pubsub)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n app.MapPost(\"/\", (Envelope envelope) =\u003e\n {\n if (envelope?.Message?.Data == null)\n {\n app.Logger.LogWarning(\"Bad Request: Invalid Pub/Sub message format.\");\n return Results.BadRequest();\n }\n\n var data = Convert.FromBase64String(envelope.Message.Data);\n var target = System.Text.Encoding.UTF8.GetString(data);\n\n app.Logger.LogInformation($\"Hello {target}!\");\n\n return Results.NoContent();\n });\n\n### Go\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // WrappedMessage is the payload of a Pub/Sub event.\n //\n // For more information about receiving messages from a Pub/Sub event\n // see: https://cloud.google.com/pubsub/docs/push#receive_push\n type WrappedMessage struct {\n \tMessage struct {\n \t\tData []byte `json:\"data,omitempty\"`\n \t\tID string `json:\"id\"`\n \t} `json:\"message\"`\n \tSubscription string `json:\"subscription\"`\n }\n\n // HelloPubSub receives and processes a Pub/Sub push message.\n func HelloPubSub(w http.ResponseWriter, r *http.Request) {\n \tvar m WrappedMessage\n \tbody, err := io.ReadAll(r.Body)\n \tdefer r.Body.Close()\n \tif err != nil {\n \t\tlog.Printf(\"io.ReadAll: %v\", err)\n \t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n \t\treturn\n \t}\n \t// byte slice unmarshalling handles base64 decoding.\n \tif err := json.Unmarshal(body, &m); err != nil {\n \t\tlog.Printf(\"json.Unmarshal: %v\", err)\n \t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n \t\treturn\n \t}\n\n \tname := string(m.Message.Data)\n \tif name == \"\" {\n \t\tname = \"World\"\n \t}\n \tlog.Printf(\"Hello %s!\", name)\n }\n\n### Java\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.example.cloudrun.Body;\n import java.util.Base64;\n import org.apache.commons.lang3.StringUtils;\n import org.springframework.http.HttpStatus;\n import org.springframework.http.ResponseEntity;\n import org.springframework.web.bind.annotation.RequestBody;\n import org.springframework.web.bind.annotation.RequestMapping;\n import org.springframework.web.bind.annotation.RequestMethod;\n import org.springframework.web.bind.annotation.RestController;\n\n // PubsubController consumes a Pub/Sub message.\n @RestController\n public class PubSubController {\n @RequestMapping(value = \"/\", method = RequestMethod.POST)\n public ResponseEntity\u003cString\u003e receiveMessage(@RequestBody Body body) {\n // Get PubSub message from request body.\n Body.Message message = body.getMessage();\n if (message == null) {\n String msg = \"Bad Request: invalid Pub/Sub message format\";\n System.out.println(msg);\n return new ResponseEntity\u003c\u003e(msg, HttpStatus.BAD_REQUEST);\n }\n\n String data = message.getData();\n String target =\n !StringUtils.isEmpty(data) ? new String(Base64.getDecoder().decode(data)) : \"World\";\n String msg = \"Hello \" + target + \"!\";\n\n System.out.println(msg);\n return new ResponseEntity\u003c\u003e(msg, HttpStatus.OK);\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n app.post('/', (req, res) =\u003e {\n if (!req.body) {\n const msg = 'no Pub/Sub message received';\n console.error(`error: ${msg}`);\n res.status(400).send(`Bad Request: ${msg}`);\n return;\n }\n if (!req.body.message) {\n const msg = 'invalid Pub/Sub message format';\n console.error(`error: ${msg}`);\n res.status(400).send(`Bad Request: ${msg}`);\n return;\n }\n\n const pubSubMessage = req.body.message;\n const name = pubSubMessage.data\n ? Buffer.from(pubSubMessage.data, 'base64').toString().trim()\n : 'World';\n\n console.log(`Hello ${name}!`);\n res.status(204).send();\n });\n\n### Python\n\n\nTo authenticate to Cloud Run, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n @app.route(\"/\", methods=[\"POST\"])\n def index():\n \"\"\"Receive and parse Pub/Sub messages.\"\"\"\n envelope = request.get_json()\n if not envelope:\n msg = \"no Pub/Sub message received\"\n print(f\"error: {msg}\")\n return f\"Bad Request: {msg}\", 400\n\n if not isinstance(envelope, dict) or \"message\" not in envelope:\n msg = \"invalid Pub/Sub message format\"\n print(f\"error: {msg}\")\n return f\"Bad Request: {msg}\", 400\n\n pubsub_message = envelope[\"message\"]\n\n name = \"World\"\n if isinstance(pubsub_message, dict) and \"data\" in pubsub_message:\n name = base64.b64decode(pubsub_message[\"data\"]).decode(\"utf-8\").strip()\n\n print(f\"Hello {name}!\")\n\n return (\"\", 204)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=cloudrun)."]]