|
| 1 | +import logging |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from localstack import config, constants |
| 5 | +from localstack.config import get_edge_url |
| 6 | +from localstack.extensions.api import Extension, http |
| 7 | +from localstack.utils.net import get_free_tcp_port |
| 8 | + |
| 9 | +from localstack_httpbin.server import HttpbinServer |
| 10 | + |
| 11 | +LOG = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class HttpbinExtension(Extension): |
| 15 | + name = "httpbin" |
| 16 | + |
| 17 | + hostname_prefix = "httpbin." |
| 18 | + |
| 19 | + server: Optional[HttpbinServer] |
| 20 | + |
| 21 | + def __init__(self): |
| 22 | + self.server = None |
| 23 | + |
| 24 | + def on_extension_load(self): |
| 25 | + level = logging.DEBUG if config.DEBUG else logging.INFO |
| 26 | + logging.getLogger("localstack_httpbin").setLevel(level=level) |
| 27 | + logging.getLogger("httpbin").setLevel(level=level) |
| 28 | + |
| 29 | + def on_platform_start(self): |
| 30 | + from localstack_httpbin.vendor.httpbin import core |
| 31 | + core.template['host'] = f"{self.get_public_hostname()}:{config.get_edge_port_http()}" |
| 32 | + |
| 33 | + self.server = HttpbinServer(get_free_tcp_port()) |
| 34 | + LOG.debug("starting httpbin on %s", self.server.url) |
| 35 | + self.server.start() |
| 36 | + |
| 37 | + def get_public_hostname(self) -> str: |
| 38 | + # FIXME: reconcile with LOCALSTACK_HOST, but this should be accessible via the host |
| 39 | + return f"{self.hostname_prefix}{constants.LOCALHOST_HOSTNAME}" |
| 40 | + |
| 41 | + def on_platform_ready(self): |
| 42 | + LOG.info("Serving httpbin on %s", get_edge_url(localstack_hostname=self.get_public_hostname())) |
| 43 | + |
| 44 | + def on_platform_shutdown(self): |
| 45 | + if self.server: |
| 46 | + self.server.shutdown() |
| 47 | + |
| 48 | + def update_gateway_routes(self, router: http.Router[http.RouteHandler]): |
| 49 | + endpoint = http.ProxyHandler(forward_base_url=self.server.url) |
| 50 | + |
| 51 | + router.add("/", host=f"{self.hostname_prefix}<host>", endpoint=endpoint) |
| 52 | + router.add("/<path:path>", host=f"{self.hostname_prefix}<host>", endpoint=endpoint) |
0 commit comments