scala 如何解析喷雾路由中的获取请求参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20011855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:51:26  来源:igfitidea点击:

How can I parse out get request parameters in spray-routing?

scalahttprequestakkaspray

提问by Kevin Colin

This is what the section of code looks like

这是代码部分的样子

    get{
      respondWithMediaType(MediaTypes.`application/json`){
          entity(as[HttpRequest]){
            obj => complete{


                println(obj)
                "ok"
            }
          }
      }
    }~

I can map the request to a spray.http.HttpRequest object and I can extract the uri from this object but I imagine there is an easier way to parse out the parameters in a get request than doing it manually.

我可以将请求映射到一个 Spray.http.HttpRequest 对象,我可以从这个对象中提取 uri,但我想有一种比手动解析获取请求中的参数更简单的方法。

For example if my get request is

例如,如果我的获取请求是

 http://localhost:8080/url?id=23434&age=24

I want to be able to get id and age out of this request

我希望能够从这个请求中获取 id 和 age

回答by 4lex1v

Actually you can do this much much better. In routing there are two directives: parameterand parameters, I guess the difference is clear, you can also use some modifiers: !and ?. In case of !, it means that this parameter must be provided or the request is going to be rejected and ?returns an option, so you can provide a default parameter in this case. Example:

实际上,您可以做得更好。在路由中有两个指令:parameterand parameters,我想区别很明显,您还可以使用一些修饰符:!and ?。如果是!,则表示必须提供此参数,否则请求将被拒绝并?返回一个选项,因此您可以在这种情况下提供默认参数。例子:

val route: Route = {
  (path("search") & get) {
    parameter("q"!) { query =>
      ....
    }
  }
}

val route: Route = {
  (path("search") & get) {
    parameters("q"!, "filter" ? "all") { (query, filter) => 
      ...
    }
  }
}