Skip to content

Instantly share code, notes, and snippets.

@ktoso
Last active November 10, 2015 15:29
Show Gist options
  • Save ktoso/bd65dd0ec9414b1b4627 to your computer and use it in GitHub Desktop.
Save ktoso/bd65dd0ec9414b1b4627 to your computer and use it in GitHub Desktop.
package example
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.{ ContentTypes, HttpRequest, HttpResponse }
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Flow, Tcp }
import akka.util.ByteString
object Example extends App with Directives {
implicit val sys = ActorSystem()
implicit val mat = ActorMaterializer()
// simple TCP echo:
val echo = Flow[ByteString]
Tcp().bindAndHandle(echo, "127.0.0.1", 8080)
// types:
// echo: Flow[ByteString, ByteString, Unit]
// low-level Http echo:
val text = ContentTypes.`text/plain`
val httpEcho = Flow[HttpRequest].map(r ⇒ HttpResponse(entity = Chunked.fromData(text, r.entity.dataBytes)))
Http().bindAndHandle(httpEcho, "127.0.0.1", 8081)
// types:
// httpEcho: Flow[HttpRequest, HttpResponse, Unit]
// r.entity.dataBytes: Source[ByteString, Unit]
// simple Http echo:
val route = extractRequest { r ⇒
complete(HttpResponse(entity = Chunked.fromData(text, r.entity.dataBytes)))
}
Http().bindAndHandle(route, "127.0.0.1", 8082)
readLine()
sys.shutdown()
sys.awaitTermination()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment