scala-akka-http代码示例


package com.gh


/**
  * Created by gavin on 17/9/11.
  */

import akka.Done
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import scala.concurrent.Future
import spray.json._
import DefaultJsonProtocol._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

import scala.io.StdIn

final case class Struct(items: Map[String, String])

final case class GN(id : String, name : String)

object WebServerDem extends App {

  implicit val orderFormat = jsonFormat1(Struct)

  implicit val gnFormat = jsonFormat2(GN)

  // def saveStruct(struct: Struct): Future[Done] = ???

  run()

  def run()  {

    implicit val system = ActorSystem("staffdem")

    implicit val materializer = ActorMaterializer()

    implicit val executionContext = system.dispatcher

    val route : Route = {
      path("hello") {
        get {
          val x = Map("Hello" -> "World", "Hello1" -> "World1", "Hello2" -> "World2", "Gavin" -> "Hacker")
          val jsonV = Struct(x)
          //val gn = GN("1","2")
          complete(jsonV)
        }
      } ~
      path("say") {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
        }
      } ~
      pathPrefix("book") {

        path(Segment) { bookId =>
          put {
            complete(bookId)
          } ~
            delete {
              complete("del")
            }
        }
      } ~
      post {
        path("struct") {
          entity(as[Struct]) { order =>
            complete(order.items.map(x => (x._1 + "_suffix", x._2 + "_suffix")))
          }
        }
      }
    }
    val bindingFuture = Http().bindAndHandle(route, "localhost", 8088)
    println(s"Server online at http://localhost:8088/\nPress RETURN to stop...")
    StdIn.readLine()
  }
}