ThreeMammals / Ocelot

.NET API Gateway
https://www.nuget.org/packages/Ocelot
MIT License
8.38k stars 1.64k forks source link

Question: How to proxy same UpstreamPathTemplate to different service base on remote ip? #1725

Closed NullRefer closed 1 year ago

NullRefer commented 1 year ago

Hello, I'm using Ocelot as API gateway. And I'm encountering a situation.

As for same UpstreamPathTemplate, I need to proxy it to difference backend service base on request ip address.

Given current configuration

{
    "DownstreamPathTemplate": "/api{catchall}",
    "DownstreamHostAndPorts": [
            {
                "Host": "my-order-webapi-service",
                "Port": 8080,
            }
        ],
    "UpstreamPathTemplate": "/order{catchall}",
    "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
}

If ip1, ip2 request for GET /order/1, it goes to my-order1-webapi-service; If ip3, ip4 request for GET /order/1, it goes to my-order2-webapi-service; And the other requests go to my-order-webapi-service.

I ask for ChatGPT, it give me an configuration of below. But ocelot starts with exception that /order{catchall} has duplicate.

How could I change my configuration to solve it?

{
    "DownstreamPathTemplate": "/api{catchall}",
    "DownstreamHostAndPorts": [
            {
                "Host": "my-order-webapi-service",
                "Port": 8080,
            }
        ],
    "UpstreamPathTemplate": "/order{catchall}",
    "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
}
{
    // for order1
    "DownstreamPathTemplate": "/api{catchall}",
    "DownstreamHostAndPorts": [
            {
                "Host": "my-order1-webapi-service",
                "Port": 8080,
            }
        ],
    "UpstreamPathTemplate": "/order{catchall}",
    "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
    "RouteClaimsRequirement": {
        "sourceIp": "ip1|ip2"
    }
},
{
    // for order2
    "DownstreamPathTemplate": "/api{catchall}",
    "DownstreamHostAndPorts": [
            {
                "Host": "my-order2-webapi-service",
                "Port": 8080,
            }
        ],
    "UpstreamPathTemplate": "/order{catchall}",
    "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
    "RouteClaimsRequirement": {
        "sourceIp": "ip3|ip4"
    }
}

Specifications