Skip to content

Instantly share code, notes, and snippets.

@kenoir
Created October 14, 2019 15:14
Show Gist options
  • Save kenoir/152d64ad61ed63968e6eef55a97fa5e6 to your computer and use it in GitHub Desktop.
Save kenoir/152d64ad61ed63968e6eef55a97fa5e6 to your computer and use it in GitHub Desktop.
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import java.io.PrintWriter
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.{StatusCodes, HttpResponse, HttpRequest, HttpEntity}
import akka.http.scaladsl.model.headers.Location
import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
def storeAndRedirect(response: HttpResponse): HttpResponse = response
.entity.contentLengthOption match {
case Some(length) if length > 10 => HttpResponse(
status = StatusCodes.PermanentRedirect,
headers = Location("http://example.com") :: Nil,
entity = HttpEntity.Empty
)
case _ => response
}
val routes = mapResponse(storeAndRedirect)(get {
complete("Hello World")
})
val binding: Future[Http.ServerBinding] =
Http().bindAndHandle(routes, "127.0.0.1", 8080)
val madeRequest = Http()
.singleRequest(HttpRequest(uri = "http://127.0.0.1:8080"))
val madeRequestResult = Await.result(madeRequest, 1.seconds)
println(madeRequestResult)
Await.result(binding, 1.seconds)
.terminate(hardDeadline = 1.seconds)
.flatMap { _ =>
system.terminate()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment