Quellcode durchsuchen

feat: 网关新增合同服务代理

天空之城 vor 3 Wochen
Ursprung
Commit
ff302884ac
2 geänderte Dateien mit 30 neuen und 1 gelöschten Zeilen
  1. 1 0
      alien_gateway/config.py
  2. 29 1
      alien_gateway/main.py

+ 1 - 0
alien_gateway/config.py

@@ -27,6 +27,7 @@ class Settings(BaseSettings):
 
 
     # 下游服务地址
     # 下游服务地址
     STORE_BASE_URL: str = os.getenv("STORE_BASE_URL")  # alien_store 服务地址
     STORE_BASE_URL: str = os.getenv("STORE_BASE_URL")  # alien_store 服务地址
+    CONTRACT_BASE_URL: str = os.getenv("CONTRACT_BASE_URL")  # alien_contract 服务地址
 
 
     # 阿里云短信配置
     # 阿里云短信配置
     ALIYUN_SMS_SIGN_NAME_CONTRACT: str = os.getenv("ALIYUN_SMS_SIGN_NAME_CONTRACT")
     ALIYUN_SMS_SIGN_NAME_CONTRACT: str = os.getenv("ALIYUN_SMS_SIGN_NAME_CONTRACT")

+ 29 - 1
alien_gateway/main.py

@@ -113,6 +113,34 @@ async def proxy_to_store(full_path: str, request: Request):
         media_type=resp.headers.get("content-type"),
         media_type=resp.headers.get("content-type"),
     )
     )
 
 
+
+@app.api_route("/api/contract/{full_path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
+async def proxy_to_contract(full_path: str, request: Request):
+    target_url = f"{settings.CONTRACT_BASE_URL}/api/contract/{full_path}"
+    client_ip = request.client.host if request.client else "-"
+    body = await request.body()
+    headers = _clean_headers(dict(request.headers))
+
+    try:
+        async with httpx.AsyncClient(timeout=30.0) as client:
+            resp = await client.request(
+                request.method,
+                target_url,
+                content=body,
+                headers=headers,
+                params=request.query_params,
+            )
+    except Exception as exc:
+        logger.error("proxy to contract failed ip=%s url=%s err=%s", client_ip, target_url, exc)
+        raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, detail="Upstream unavailable")
+
+    return Response(
+        content=resp.content,
+        status_code=resp.status_code,
+        headers=_clean_headers(resp.headers),
+        media_type=resp.headers.get("content-type"),
+    )
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     import uvicorn
     import uvicorn
-    uvicorn.run(app, host="0.0.0.0", port=33333)
+    uvicorn.run(app, host="0.0.0.0", port=33333)