Gestore per i messaggi Pub/Sub
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Servizio per la gestione dei messaggi inviati da una sottoscrizione push di Cloud Pub/Sub.
Per saperne di più
Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:
Esempio di codice
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","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)."]]