Last active
February 16, 2018 16:42
-
-
Save mathieuancelin/02844ecd87c0ca1001079749ee6e27d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model.headers._ | |
import akka.http.scaladsl.model._ | |
import akka.http.scaladsl.util.FastFuture | |
import akka.stream.ActorMaterializer | |
import akka.util.ByteString | |
import scala.concurrent._ | |
import kaleidoscope._ | |
implicit val system = ActorSystem() | |
implicit val executor = system.dispatcher | |
implicit val materializer = ActorMaterializer() | |
implicit val http = Http(system) | |
def JsonResponse(status: Int, json: String): HttpResponse = HttpResponse( | |
status, | |
entity = HttpEntity(ContentTypes.`application/json`, json) | |
) | |
def AsyncJsonResponse(status: Int, json: String): Future[HttpResponse] = | |
FastFuture.successful(JsonResponse(status, json)) | |
def handler(request: HttpRequest): Future[HttpResponse] = { | |
(request.method, request.header[`Content-Type`].map(_.contentType), request.uri.path.toString) match { | |
case (HttpMethods.GET, _, r"/api/users/$userId@([^/]+)") => AsyncJsonResponse(200, s"""{"userId":"$userId"}""") | |
case (HttpMethods.POST, Some(ContentTypes.`application/json`), r"/api/users") => { | |
request.entity.dataBytes.runFold(ByteString.empty)(_ ++ _).map { body => | |
JsonResponse(201, body.utf8String) | |
} | |
} | |
case _ => AsyncJsonResponse(404, """{"error":"not found"}""") | |
} | |
} | |
http.bindAndHandleAsync(handler, "0.0.0.0", 8888) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment