Created
March 23, 2017 00:45
-
-
Save animatedlew/a82bfbded0cfcc6c0a33377692d829a3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.server.Route | |
import akka.stream.ActorMaterializer | |
import akka.http.scaladsl.server.Directives._ | |
import akka.http.scaladsl.model.StatusCodes | |
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ | |
import spray.json.DefaultJsonProtocol._ | |
import spray.json._ | |
import scala.collection.mutable | |
import scala.concurrent.{ExecutionContextExecutor, Future} | |
import scala.io.StdIn | |
object WebServer { | |
implicit val system: ActorSystem = ActorSystem.create() | |
implicit val materializer = ActorMaterializer() | |
implicit val executionContext: ExecutionContextExecutor = system.dispatcher | |
case class Item(id: Option[Long], name: Option[String], price: Option[Double], quantity: Option[Long]) | |
implicit val format: RootJsonFormat[Item] = jsonFormat4(Item) | |
val db: mutable.Map[Long, Item] = mutable.Map[Long, Item]() | |
def main(args: Array[String]): Unit = { | |
val bindingFuture = startup | |
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...") | |
StdIn.readLine() | |
shutdown(bindingFuture) | |
} | |
private def startup = { | |
val route: Route = | |
pathSingleSlash { get { complete("Ok!") } } ~ | |
pathPrefix("item" / LongNumber) { id => | |
get { | |
db.get(id) match { | |
case Some(item) => complete(item) | |
case _ => complete(StatusCodes.NotFound) | |
} | |
} | |
} ~ | |
delete { | |
path("item") { | |
entity(as[Item]) { item => | |
db -= item.id.getOrElse(-1L) | |
complete(StatusCodes.NoContent) | |
} | |
} | |
} ~ | |
put { | |
path("item") { | |
entity(as[Item]) { | |
case item @ Item(Some(id), _, _, _) => | |
db(id) = item | |
complete(Map("id" -> id)) | |
case _ => | |
complete(StatusCodes.BadRequest) | |
} | |
} | |
} ~ | |
post { | |
path("item") { | |
entity(as[Item]) { item => | |
val id = db.keys.size + 1 | |
db.update(id, item.copy(id = Some(id))) | |
complete(Map("id" -> id)) | |
} | |
} | |
} ~ | |
get { path("items") { complete(db.values.toList) } } | |
Http().bindAndHandle(route, "localhost", 8080) | |
} | |
private def shutdown(bindingFuture: Future[Http.ServerBinding]) = | |
bindingFuture.flatMap(_.unbind()).onComplete(_ => system.terminate()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment