我有这个简单的测试Scala应用程序,它阻止http请求:
build.sbt
name := "hello"
version := "1.0"
scalaVersion := "2.11.2"
libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.4.0-M1"
Run Code Online (Sandbox Code Playgroud)
Test.scala
import play.api.libs.json._
import play.api.libs.ws._
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
object Test {
def main(args: Array[String]) = {
val wsClient = WS.client
val body = getBody(wsClient.url("http://example.com/").get())
println(s"body: $body")
}
def getBody(future: Future[WSResponse]) = {
val response = Await.result(future, Duration.Inf);
if (response.status != 200)
throw new Exception(response.statusText);
response.body
}
}
Run Code Online (Sandbox Code Playgroud)
此应用程序失败:
Exception in thread "main" java.lang.RuntimeException: There is no started application
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
我在一些源代码中遇到了以下定义:
case class Task(uuid: String = java.util.UUID.randomUUID().toString, n: Int)
Run Code Online (Sandbox Code Playgroud)
这里第一个参数声明为默认值,但我不明白如何使用这个默认值创建实例。如果我不能像那样传递第一个参数,Task(1)
那么我肯定会得到编译错误。
但是,以下更改工作正常:
case class Task(n: Int, uuid: String = java.util.UUID.randomUUID().toString)
Run Code Online (Sandbox Code Playgroud)
但是,正如定义中所示,这里uuid
是第一个参数。
我的问题是关于Ktor中路由功能背后的全局情况;设计具有大量路由的API时具有很高的可扩展性。
如果我创建这样的应用程序:
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.request.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
fun Application.routingExample() {
intercept(ApplicationCallPipeline.Call){
if (call.request.uri == "/") call.respondText("User call for /")
}
}
fun main(args: Array<String>) {
embeddedServer(Netty, 8080, watchPaths = listOf("Routing"), module = Application::routingExample).start()
}
Run Code Online (Sandbox Code Playgroud)
如果我的api / app路由数量少,那没关系。但是,我应该以哪种样式将这种方法扩展到大量路由(例如30条路由和控制器功能)。
我将有多种选择:
大型路由功能:我将拥有一个Application.routingExample
可以容纳所有路由的大型功能,因此无需更新主路由。
一个大型的主要功能:将有一个大型功能,可以容纳对其他较小功能的调用;但这将是重复的;至于API,我想在同一端口中提供它们。
所以我的问题是关于编码风格的:有没有一种方法可以分解路由控制器的关系?