Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 759
Kevin Colin Avatar asked Nov 15 '13 22:11

Kevin Colin


1 Answers

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) => 
      ...
    }
  }
}
like image 164
4lex1v Avatar answered Oct 24 '22 07:10

4lex1v