Skip to content

Instantly share code, notes, and snippets.

@OlegIlyenko
Created June 21, 2015 12:42
Show Gist options
  • Save OlegIlyenko/c4c7199e6eba3d1dff37 to your computer and use it in GitHub Desktop.
Save OlegIlyenko/c4c7199e6eba3d1dff37 to your computer and use it in GitHub Desktop.
Example of akka-http server with generic OPTIONS method handling
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"
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)
}
@izmailoff
Copy link

Great idea, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment