spray-routing

spray路由

spray-routing模塊提供一個高級的,很靈活的路由DSL,來定義RESTful web服務。一般將它用在spray-can HttpServer之上,或在servlet容器內和spray-servlet一塊兒用。 web

最小的示例

這是一個完整的,基本的spray-routing應用: json

import spray.routing.SimpleRoutingApp

object Main extends App with SimpleRoutingApp {
  startServer(interface = "localhost", port = 8080) {
    path("hello") {
      get {
        complete {
          <h1>Say hello to spray</h1>
        }
      }
    }
  }
}

它在本地啓動一個spray-can HttpServer 並給GET請求/hello 回覆一個簡單的響應。

更長的示例

如下是一個spray-routing路由定義,它試圖展現幾個特性。由此產生的服務並不真的作有用的事情,可是它的定義應該能給你一個感受,用spray-routing定義的實際API看起來是這樣的: api

import scala.concurrent.duration.Duration
import spray.routing.HttpService
import spray.routing.authentication.BasicAuth
import spray.routing.directives.CachingDirectives._
import spray.httpx.encoding._

trait LongerService extends HttpService with MyApp {

  val simpleCache = routeCache(maxCapacity = 1000, timeToIdle = Duration("30 min"))

  val route = {
    path("orders") {
      authenticate(BasicAuth(realm = "admin area")) { user =>
        get {
          cache(simpleCache) {
            encodeResponse(Deflate) {
              complete {
                // marshal custom object with in-scope marshaller
                getOrdersFromDB
              }
            }
          }
        } ~
        post {
          (decodeRequest(Gzip) | decodeRequest(NoEncoding)) {
            // unmarshal with in-scope unmarshaller
            entity(as[Order]) { order =>
              // transfer to newly spawned actor
              detachTo(singleRequestServiceActor) {
                complete {
                  // ... write order to DB
                  "Order received"
                }
              }
            }
          }
        }
      }
    } ~
    // extract URI path element as Int
    pathPrefix("order" / IntNumber) { orderId =>
      path("") {
        // method tunneling via query param
        (put | parameter('method ! "put")) {
          // form extraction from multipart or www-url-encoded forms
          formFields('email, 'total.as[Money]).as(Order) { order =>
            complete {
              // complete with serialized Future result
              (myDbActor ? Update(order)).mapTo[TransactionResult]
            }
          }
        } ~
        get {
          // JSONP support
          jsonpWithParameter("callback") {
            // use in-scope marshaller to create completer function
            produce(instanceOf[Order]) { complete => ctx =>
              processOrderRequest(orderId, complete)
            }
          }
        }
      } ~
      path("items") {
        get {
          // parameters to case class extraction
          parameters('size.as[Int], 'color ?, 'dangerous ? "no")
                  .as(OrderItem) { orderItem =>
            // ... route using case class instance created from
            // required and optional query parameters
          }
        }
      }
    } ~
    path("documentation") {
      // cache responses to GET requests
      cache(simpleCache) {
        // serve up static content from a JAR resource
        encodeResponse(Gzip) {
          getFromResourceDirectory("docs")
        }
      }
    } ~
    path("oldApi" / Rest) { path =>
      redirect("http://oldapi.example.com/" + path)
    }
  }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息