在 VPC 网络中的内部 HTTP 端点上接收 Pub/Sub 事件

在 Virtual Private Cloud (VPC) 网络中创建内部 HTTP 端点,该端点使用 Eventarc 接收 Pub/Sub 消息事件。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

如需向 Eventarc 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                str(self.path), str(self.headers), post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=80):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    http_server = server_class(server_address, handler_class)
    logging.info('Starting HTTP Server at port %d...\n', port)
    try:
        http_server.serve_forever()
    except KeyboardInterrupt:
        pass
    http_server.server_close()
    logging.info('Stopping HTTP Server...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器