scalaspray

Spray: routing - understand the difference between path and pathPrefix


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.


Solution

  • In docs :

    path(x): is equivalent to rawPathPrefix(slash().concat(segment(x)).concat(pathEnd())). It matches a leading slash followed by x and then the end.

    pathPrefix(x): is equivalent to rawPathPrefix(slash().concat(segment(x))). It matches a leading slash followed by x and then leaves a suffix unmatched.