发送多条路线到相同目的地地址

huangapple go评论49阅读模式
英文:

Send multiple routes to the same destination address

问题

在yarp中是否可以匹配多个路径?

例如,我有这个:

endpoints.Map("/place/{**catch-all}", async httpContext =>
{
    var error = await forwarder.SendAsync(httpContext, "https://maps.googleapis.com/maps/api/",
        httpClient, requestConfig, transformer);
    // Check if the operation was successful
    if (error != ForwarderError.None)
    {
        var errorFeature = httpContext.GetForwarderErrorFeature();
        var exception = errorFeature.Exception;
    }
});

但我想为"/geocode/{**catch-all}"做同样的事情,避免重复代码。

因为路由只是http://localhost/geocode...或http://localhost/place...

所以在它之前没有任何内容可以匹配。我可以在前端添加一些内容,比如http://localhost/proxyme/place/...,但是在我的CustomTransformer中,httpContext.Request.Path中有"proxyme/",我不知道如何在这里使用它之前删除它:proxyRequest.RequestUri = RequestUtilities.MakeDestinationAddress("https://maps.googleapis.com/maps/api", httpContext.Request.Path, queryContext.QueryString);,而不只是进行原始字符串操作来删除"proxyme/"。所以如果有一种优雅的方法来删除httpContext.Request.Path中的"proxyme/",那可能是另一种选择。

英文:

Can I match multiple paths in yarp?

E.g. I have this:

endpoints.Map("/place/{**catch-all}", async httpContext =>
{
    var error = await forwarder.SendAsync(httpContext, "https://maps.googleapis.com/maps/api/",
        httpClient, requestConfig, transformer);
    // Check if the operation was successful
    if (error != ForwarderError.None)
    {
        var errorFeature = httpContext.GetForwarderErrorFeature();
        var exception = errorFeature.Exception;
    }
});

But I would like to do the same for "/geocode/{**catch-all}", without code duplication.

Because the route is just http://localhost/geocode... or http://localhost/place...

So there is nothing before it to match on. I can add something before it instead like http://localhost/proxyme/place/... in my front end, but then in my CustomTransformer, httpContext.Request.Path has "proxyme/" in it and I don't know how to remove it for use here: proxyRequest.RequestUri = RequestUtilities.MakeDestinationAddress("https://maps.googleapis.com/maps/api", httpContext.Request.Path, queryContext.QueryString); without just doing primitive string operations to delete "proxyme/". So that could be the other option if there is an elegant way to delete "proxyme/" from the httpContext.Request.Path.

答案1

得分: 1

只需在这两个路由中重复使用相同的方法:

RequestDelegate handler = async httpContext =>
{
    var error = await forwarder.SendAsync(httpContext, "https://maps.googleapis.com/maps/api/",
        httpClient, requestConfig, transformer);
    // 检查操作是否成功
    if (error != ForwarderError.None)
    {
        var errorFeature = httpContext.GetForwarderErrorFeature();
        var exception = errorFeature.Exception;
    }
}

endpoints.Map("/place/{**catch-all}", handler);
endpoints.Map("/geocode/{**catch-all}", handler);
英文:

Just reuse the same method in the 2 routes:

RequestDelegate handler = async httpContext =>
{
    var error = await forwarder.SendAsync(httpContext, "https://maps.googleapis.com/maps/api/",
        httpClient, requestConfig, transformer);
    // Check if the operation was successful
    if (error != ForwarderError.None)
    {
        var errorFeature = httpContext.GetForwarderErrorFeature();
        var exception = errorFeature.Exception;
    }
}

endpoints.Map("/place/{**catch-all}", handler);
endpoints.Map("/geocode/{**catch-all}", handler);

答案2

得分: -2

我想在"/geocode/{**catch-all}"上执行相同操作,而不会重复代码。

考虑使用自定义路由约束1

builder.Services.AddRouting(options =>
    options.ConstraintMap.Add("MyConstraint", typeof(MyConstraint)));

.......
app.Map("/{my:MyConstraint}/{**catch-all}", () => {.....});

你也可以像文档中所示定义一个处理程序:

var handler = (HttpContext context) =>
{
   ......
};

app.Map("/Parttern1/{**catch-all}", handler);
app.Map("/Parttern2/{**catch-all}", handler);
英文:

> I would like to do the same for "/geocode/{**catch-all}", without code
> duplication.

Consider custom route constraint:

builder.Services.AddRouting(options =>
    options.ConstraintMap.Add("MyConstraint", typeof(MyConstraint)));

 .......
 app.Map("/{my:MyConstraint}/{**catch-all}", () => {.....});





public class MyConstraint : IRouteConstraint
    {
        private static readonly string[] AllowedValues = new string[] { "place", "geocode" };

        public bool Match(
            HttpContext? httpContext, IRouter? route, string routeKey,
            RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (!values.TryGetValue(routeKey, out var routeValue))
            {
                return false;
            }

            var routeValueString = Convert.ToString(routeValue, CultureInfo.InvariantCulture);

            if (routeValueString is null)
            {
                return false;
            }

            return AllowedValues.Contains(routeValueString, StringComparer.InvariantCultureIgnoreCase);
        }
    }

Or define a handler as the document

var handler = (HttpContext context) =>
{
   ......
};

app.Map("/Parttern1/{**catch-all}", handler);
app.Map("/Parttern2/{**catch-all}", handler);

huangapple
  • 本文由 发表于 2023年7月17日 15:28:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定