Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spray: routing - understand the difference between path and pathPrefix

Tags:

scala

spray

import akka.actor.Actor
import spray.routing.HttpService
import spray.http._
import MediaTypes._
import spray.json._
import spray.routing.directives.CachingDirectives._
import spray.httpx.encoding._

trait MarginEvaluationService extends HttpService {
  import ClassSerializer._
  import spray.httpx.SprayJsonSupport._
  val myRoute = {

      pathPrefix("hello") {
        get {
          respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here
            complete {
              <html>
                <body>
                  <h1>Say hello to <i>spray-routing</i> on <i>spray-can</i>!</h1>
                </body>
              </html>
            }
          }
        }
      }
      ~
      pathPrefix("testjson") {
        get {
          entity(as[TestC]) { c =>
            respondWithMediaType(`application/json`) {
              complete(c)
            }
          }
        }
      }
   }
}

The route is bugged:

Error:(49, 1) illegal start of simple expression pathPrefix("testjson") { ^

What is the difference between path and pathPrefix? I am not sure if the ~ operator is not properly included.

like image 516
NoIdeaHowToFixThis Avatar asked Aug 06 '15 14:08

NoIdeaHowToFixThis


1 Answers

path is a final path, while pathPrefix can be subsequently combined with other path segments using the DSL.

If you want to match exactly /hello you should use path("hello").

pathPrefix is convenient in cases like

pathPrefix("hello") {
  path("foo") {
    complete("foo")
  } ~
  path("bar") {
    complete("bar")
  }
}

which will match /hello/foo and /hello/bar.


That having being said, I suspect the error you're getting is simply the scala parser not getting along with the DSL.

Can you try moving the ~ on the same line as the closing brace? I think the parser is inferring a semicolon, so it's really understanding that piece of code as

pathPrefix("hello") {
    get {
      respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here
        complete {
          <html>
            <body>
              <h1>Say hello to <i>spray-routing</i> on <i>spray-can</i>!</h1>
            </body>
          </html>
        }
      }
    }
  };
  ~
  pathPrefix("testjson") {
    get {
      entity(as[TestC]) { c =>
        respondWithMediaType(`application/json`) {
          complete(c)
        }
      }
    }
  }
like image 56
Gabriele Petronella Avatar answered Sep 28 '22 16:09

Gabriele Petronella