Http Server in Scala

Here’s the translation of the HTTP Server example from Go to Scala, with explanations in Markdown format suitable for Hugo:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

import scala.io.StdIn

object HttpServer {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("my-system")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val route =
      path("hello") {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "hello\n"))
        }
      } ~
      path("headers") {
        get {
          extractRequest { request =>
            val headerString = request.headers
              .map(h => s"${h.name()}: ${h.value()}")
              .mkString("\n")
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, headerString))
          }
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8090)

    println(s"Server online at http://localhost:8090/\nPress RETURN to stop...")
    StdIn.readLine()
    bindingFuture
      .flatMap(_.unbind())
      .onComplete(_ => system.terminate())
  }
}

Writing a basic HTTP server in Scala can be done using the Akka HTTP library, which provides a high-level, elegant way to create HTTP servers.

In this example, we’re using Akka HTTP to create a server with two routes: /hello and /headers.

First, we import the necessary Akka HTTP modules and other required Scala libraries.

The main function is the entry point of our application. We set up an ActorSystem, ActorMaterializer, and ExecutionContext, which are required for Akka HTTP to function.

We define our routes using Akka HTTP’s DSL (Domain Specific Language). The route value contains two paths:

  1. The /hello path simply returns “hello\n” as the response.
  2. The /headers path reads all the HTTP request headers and echoes them into the response body.

After defining the routes, we bind the server to localhost on port 8090 using Http().bindAndHandle(). This starts the server and returns a Future that completes when the server is bound to the specified address and port.

We then print a message indicating that the server is running and wait for user input to stop the server. When the user presses RETURN, we unbind the server and terminate the actor system.

To run the server:

  1. Save the code in a file named HttpServer.scala.
  2. Compile and run the code using SBT (Simple Build Tool) or your preferred Scala build tool.
  3. Access the server using curl or a web browser:
$ curl http://localhost:8090/hello
hello

$ curl http://localhost:8090/headers
Host: localhost:8090
User-Agent: curl/7.64.1
Accept: */*

This example demonstrates how to create a simple HTTP server in Scala using Akka HTTP, handling different routes and working with request headers.