|
| 1 | +class SingletonMeta(type): |
| 2 | + """ |
| 3 | + The Singleton class can be implemented in different ways in Python. Some |
| 4 | + possible methods include: base class, decorator, metaclass. We will use the |
| 5 | + metaclass because it is best suited for this purpose. |
| 6 | + """ |
| 7 | + _instances = {} |
| 8 | + _singleton = True |
| 9 | + |
| 10 | + def __call__(cls, *args, **kwargs): |
| 11 | + if cls not in cls._instances or not cls._singleton: |
| 12 | + cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs) |
| 13 | + else: |
| 14 | + cls._instances[cls].__init__(*args, **kwargs) |
| 15 | + |
| 16 | + return cls._instances[cls] |
| 17 | + |
| 18 | + |
| 19 | +class ReverseProxied: |
| 20 | + """ |
| 21 | + Create a Proxy pattern https://microservices.io/patterns/apigateway.html. |
| 22 | + You can run the microservice A in your local machine in http://localhost:5000/my-endpoint/ |
| 23 | + If you deploy your microservice, in some cases this microservice run behind a cluster, a gateway... and this |
| 24 | + gateway redirect traffic to the microservice with a specific path like yourdomian.com/my-ms-a/my-endpoint/. |
| 25 | + This class understand this path if the gateway send a specific header |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, app): |
| 29 | + self.app = app |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def _extract_prefix(environ): |
| 33 | + """ |
| 34 | + Get Path from environment from: |
| 35 | + - Traefik with HTTP_X_SCRIPT_NAME https://docs.traefik.io/v2.0/middlewares/headers/ |
| 36 | + - Nginx and Ingress with HTTP_X_SCRIPT_NAME https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ |
| 37 | + - Apache with HTTP_X_SCRIPT_NAME https://stackoverflow.com/questions/55619013/proxy-and-rewrite-to-webapp |
| 38 | + - Zuul with HTTP_X_FORWARDER_PREFIX https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html |
| 39 | + :param environ: |
| 40 | + :return: |
| 41 | + """ |
| 42 | + # Get path from Traefik, Nginx and Apache |
| 43 | + path = environ.get('HTTP_X_SCRIPT_NAME', '') |
| 44 | + if not path: |
| 45 | + # Get path from Zuul |
| 46 | + path = environ.get('HTTP_X_FORWARDED_PREFIX', '') |
| 47 | + if path and not path.startswith("/"): |
| 48 | + path = "/" + path |
| 49 | + return path |
| 50 | + |
| 51 | + def __call__(self, environ, start_response): |
| 52 | + script_name = self._extract_prefix(environ) |
| 53 | + if script_name: |
| 54 | + environ['SCRIPT_NAME'] = script_name |
| 55 | + path_info = environ['PATH_INFO'] |
| 56 | + if path_info.startswith(script_name): |
| 57 | + environ['PATH_INFO'] = path_info[len(script_name):] |
| 58 | + |
| 59 | + scheme = environ.get('HTTP_X_SCHEME', '') |
| 60 | + if scheme: |
| 61 | + environ['wsgi.url_scheme'] = scheme |
| 62 | + return self.app(environ, start_response) |
0 commit comments