Created
June 21, 2015 12:42
-
-
Save OlegIlyenko/c4c7199e6eba3d1dff37 to your computer and use it in GitHub Desktop.
Example of akka-http server with generic OPTIONS method handling
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
name := "akka-http-options-example" | |
version := "0.1.0-SNAPSHOT" | |
scalaVersion := "2.11.6" | |
scalacOptions ++= Seq("-deprecation", "-feature") | |
libraryDependencies += | |
"com.typesafe.akka" %% "akka-http-experimental" % "1.0-RC3" |
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.stream.ActorFlowMaterializer | |
import akka.http.scaladsl.model.headers._ | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.server._ | |
import akka.http.scaladsl.model.StatusCodes._ | |
import akka.http.scaladsl.server.Directives._ | |
object OptionsMethod extends App { | |
implicit val system = ActorSystem("my-options") | |
implicit val materializer = ActorFlowMaterializer() | |
implicit def rejectionHandler = | |
RejectionHandler.newBuilder().handleAll[MethodRejection] { rejections => | |
val methods = rejections map (_.supported) | |
lazy val names = methods map (_.name) mkString ", " | |
respondWithHeader(Allow(methods)) { | |
options { | |
complete(s"Supported methods : $names.") | |
} ~ | |
complete(MethodNotAllowed, s"HTTP method not allowed, supported methods: $names!") | |
} | |
} | |
.result() | |
val route: Route = | |
pathPrefix("orders") { | |
pathEnd { | |
get { | |
complete("Order 1, Order 2") | |
} ~ | |
post { | |
complete("Order saved") | |
} | |
} ~ | |
path(LongNumber) { id => | |
put { | |
complete(s"Order $id") | |
} | |
} | |
} | |
Http().bindAndHandle(route, "0.0.0.0", 8080) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great idea, thanks for sharing!