仆人中的重定向 [英] Redirections in Servant

查看:56
本文介绍了仆人中的重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使Servant处理程序通过重定向做出响应的适当方法是什么?我在导航REST应用程序中工作,我想响应POST请求,该请求创建具有重定向到相应GET资源列表路径的资源.因此,例如 POST/foos 应该在创建foo之后重定向到 GET/foos .我在文档中找不到明确的方法.

What's the appropriate way to make a Servant handler respond with a redirection? I am working in a navigation REST app and I would like to respond to POST requests that create resources with a redirection to the corresponding GET resource list paths. So for instance POST /foos should redirect to GET /foos after creating a foo. I could not find a clear way to do that in the documentation.

推荐答案

有一个简单(但有点怪异)的答案,以及使第一个选项过时的线索(实际上是第三个更好的选项).

There is one simple (but slightly hacky) answer, and a lead for making the first option obsolete ( and a third, better option, actually).

当前的典型解决方案是简单地使用以下事实:Handler monad具有MonadError ServantErr实例,并且ServantErr是非常通用的响应类型",实际上可以描述HTTP响应.应用程序错误,但实际上还是重定向或许多其他事情.因此,您可以执行类似throwError $ err301 { errHeaders = [("Location", "https://haskell.org/")] }的操作.这很丑陋,因为我们劫持了一些成功工作流程的错误输出"位.但这有效,并且只需一行代码.

The current typical solution for this is to simply use the fact that the Handler monad has a MonadError ServantErr instance, and that ServantErr is a very general "response type" that can indeed describe the HTTP response for an application error, but also a redirect or many other things really. So you can do something like throwError $ err301 { errHeaders = [("Location", "https://haskell.org/")] }. It's ugly because we hijack the "erroring out" bit for some successful workflow. But it works, and is a single line of code.

我已经探索了替代方法,使您可以将类型安全链接与重定向混合使用,以轻松地重定向到应用程序的其他端点/页面.现在,这已经过时了,但可以使它正常工作而不会带来太多麻烦.

I have explored alternative approaches, that let you mix type-safe links with redirects to easily redirect to other endpoints/pages of your app. This is outdated now but could probably be made to work without toooo much trouble.

看到这个问题,我刚才想到了第三个选择.花了一些时间来尝试它,看起来像它的作品!您可以在此要点中查看使用示例的代码.如果您有任何问题,请告诉我.我们可能想将其中一些添加到仆人中.如果您认为这足够好,请随时在问题跟踪器中进行介绍.该方法的要旨是定义具有正确形状的自定义PostRedirect(无响应主体,具有您选择的类型的Location标头,并由您要重定向使用的状态代码进行参数化),以及返回之前适当包装位置的小功能.

And upon seeing this question, I just now thought of a third option. Took a bit of time to experiment with it and looks like it works! You can see the code with an example of using it in this gist. Let me know if you have any question. We might want to add some of this to servant. Feel free to bring it up on the issue tracker if you think this is good enough. The gist of this approach is to define a custom PostRedirect that has the right shape (no response body, a Location header with a type of your choice, and parametrized by the status code that you want your redirect to use), and a little function that wraps the location appropriately before returning.

这篇关于仆人中的重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆