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

青春壹個敷衍的年華 提交于 2019-12-04 10:20:04

问题


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.

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


回答1:


Actually you can do this much much better. In routing there are two directives: parameter and 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:

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

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


来源:https://stackoverflow.com/questions/20011855/how-can-i-parse-out-get-request-parameters-in-spray-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!