url-router API设计问题

发布于 2024-10-09 16:24:39 字数 706 浏览 0 评论 0原文

我正在为 Web 框架创建一个 URL 路由器。尝试使使用尽可能友好。 API 看起来像这样:

Route[] Routes = {
    new Route(@"/user:(?<id>\d+)", "UserController.View")
};

它将把与该正则表达式匹配的任何 Url 路由到该方法,这可能看起来像这样:

public class UserController : Controller
{
    public void View(int id)
    {
        // code here
    }
}

它自动处理类型转换。

(?...) 与该方法采用的参数之间存在相关性。 View() 函数必须接受名称捕获提供的所有参数。但是,它可以接受更多参数,只要它们是可选的。例如,该正则表达式还将匹配函数 View(int id, int extraArg=2),因为我们实际上并不需要 extraArg 来调用该函数。

问题是,该路由是否也应该与函数 View() 匹配——不带参数? id 捕获很容易被丢弃,我们仍然可以很好地调用该函数。或者它应该抛出异常(就像现在一样)?

I'm creating a Url router for a web framework. Trying to make as friendly to use as possible. The API looks something like:

Route[] Routes = {
    new Route(@"/user:(?<id>\d+)", "UserController.View")
};

Where it would route any Url that matches that regex to that method, which might look something like this:

public class UserController : Controller
{
    public void View(int id)
    {
        // code here
    }
}

It handles the type-casting automatically.

There is a correlation between (?<id>...) and the arguments that the method takes. The View() function must accept all the arguments provided by the name captures. However, it can accept more arguments as long as they're optional. For example, that regex would also match the function View(int id, int extraArg=2), since we don't really need the extraArg to call the function.

The question is, should that route also match the function View() -- with no arguments? The id capture can easily be discarded and we can still call the function just fine. Or should it throw an exception (as it does presently)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

书间行客 2024-10-16 16:24:39

采用最好的编程方法:您不希望用户遇到任何错误。
看到用户可能在任何阶段意外/故意添加额外的参数,我只会采用必要的参数,而忽略其余的。

Take the best programming approach: you don't want the user to encounter any errors.
Seeing that the user could accidentally/deliberately put extra parameters in at any stage, I'd just take the necessary ones, and ignore the rest.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文