Pub/Sub 메시지 핸들러
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Cloud Pub/Sub 푸시 구독으로 전달된 메시지를 처리하는 서비스입니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
C#
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Go
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","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)."]]