/docs/serving/samples/hello-world/helloworld-scala/src/main/scala/klang/HelloWorldScala.scala

https://github.com/knative/docs · Scala · 51 lines · 36 code · 6 blank · 9 comment · 0 complexity · bb22ab7cb97e6f19925d5df98e83f4f9 MD5 · raw file

  1. package klang
  2. import akka.actor.ActorSystem
  3. import akka.event.LoggingAdapter
  4. import akka.http.scaladsl.Http
  5. import akka.http.scaladsl.model._
  6. import ContentTypes._
  7. import akka.http.scaladsl.server.Directives._
  8. import akka.stream.{ActorMaterializer, Materializer}
  9. import scala.concurrent.ExecutionContext
  10. import scala.util.{Failure, Success}
  11. object HelloWorldScala {
  12. def main(args: Array[String]): Unit = {
  13. // Creates and initializes an Akka Actor System
  14. implicit val system: ActorSystem = ActorSystem("HelloWorldScala")
  15. // Creates and initializes a Materializer to be used for the Akka HTTP Server
  16. implicit val mat: Materializer = ActorMaterializer()
  17. // Specifies where any Futures in this code will execute
  18. implicit val ec: ExecutionContext = system.dispatcher
  19. // Obtains a logger to be used for the sample
  20. val log: LoggingAdapter = system.log
  21. // Obtains a reference to the configuration for this application
  22. val config = system.settings.config
  23. // These are read from the application.conf file under `resources`
  24. val message = config.getString("helloworld.message")
  25. val host = config.getString("helloworld.host")
  26. val port = config.getInt("helloworld.port")
  27. // Here we define the endpoints exposed by this application
  28. val serviceRoute =
  29. path("") {
  30. get {
  31. log.info("Received request to HelloWorldScala")
  32. complete(HttpEntity(`text/html(UTF-8)`, message))
  33. }
  34. }
  35. // Here we create the Http server, and bind it to the host and the port,
  36. // so we can serve requests using the route(s) we defined previously.
  37. val binding = Http().bindAndHandle(serviceRoute, host, port) andThen {
  38. case Success(sb) =>
  39. log.info("Bound: {}", sb)
  40. case Failure(t) =>
  41. log.error(t, "Failed to bind to {}:{}—shutting down", host, port)
  42. system.terminate()
  43. }
  44. }
  45. }