Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active October 5, 2023 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/a0bd3b9fae099af71da1f05156387306 to your computer and use it in GitHub Desktop.
Save xuwei-k/a0bd3b9fae099af71da1f05156387306 to your computer and use it in GitHub Desktop.
playframework Scala 3 hello world
scalaVersion := "3.3.1"
run / fork := true
// nettyの方にするとakka-http依存がなくなって全てScala 3になる
// akka依存はあるが有料になる前の古いOSSライセンスなのでしばらく安心
libraryDependencies += "com.typesafe.play" %% "play-netty-server" % "2.9.0-RC3"
libraryDependencies += "org.slf4j" % "slf4j-simple" % "2.0.9" // 最低限雑にログ出すため
import play.api.BuiltInComponents
import play.api.Mode
import play.api.mvc._
import play.api.routing._
import play.api.routing.sird._
import play.core.server.NettyServer
import play.core.server.ServerConfig
object Main {
// 1つのScalaファイルで済むので、
// routesファイルを別に書かずにScalaコードで直接DSL書く方法で書いてる
// https://www.playframework.com/documentation/2.8.x/ScalaSirdRouter
private def router(c: BuiltInComponents): PartialFunction[RequestHeader, Handler] = {
case GET(p"/$path") => c.defaultActionBuilder {
Results.Ok(s"hello $path") // ほぼechoするような意味ない実装
}
}
private val config = ServerConfig(
port = Some(0), // ゼロは雑に空いてる任意portで立ち上げの意味。省略したら9000
mode = Mode.Test // 真面目な用途の場合は避けるべきだが、Testだとapplication.conf必要ないので
)
def main(args: Array[String]): Unit = {
val server = NettyServer.fromRouterWithComponents(config)(router)
val port = server.httpPort.getOrElse(sys.error("not available http port"))
println(s"start http://localhost:${port}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment