Created
September 5, 2018 05:51
-
-
Save sebastianharko/a9f7381c4bcaac87fb5d1ab1cee30351 to your computer and use it in GitHub Desktop.
what about this
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.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller} | |
import akka.http.scaladsl.model.headers.RawHeader | |
import akka.http.scaladsl.model.{HttpRequest, MediaTypes} | |
import akka.http.scaladsl.server.Directives._ | |
import akka.stream.ActorMaterializer | |
import de.heikoseeberger.akkahttpjson4s.Json4sSupport | |
import org.json4s | |
import org.json4s.DefaultFormats | |
import scala.io.StdIn | |
sealed trait MyType { | |
val body: String | |
} | |
case class SomeClass(body: String) extends MyType | |
object WebServer extends Json4sSupport { | |
def main(args: Array[String]) { | |
implicit val serialization = json4s.jackson.Serialization // or native.Serialization | |
implicit val formats = DefaultFormats | |
implicit val system = ActorSystem("my-system") | |
implicit val materializer = ActorMaterializer() | |
// needed for the future flatMap/onComplete in the end | |
implicit val executionContext = system.dispatcher | |
def plainText[A <: MyType]: ToEntityMarshaller[A] = { | |
PredefinedToEntityMarshallers.stringMarshaller(MediaTypes.`text/plain`).compose(_.body) | |
} | |
def json[A <: MyType]: ToEntityMarshaller[A] = { | |
PredefinedToEntityMarshallers.stringMarshaller(MediaTypes.`application/json`).compose(serialization.write(_)) | |
} | |
implicit def marshaller[A <: MyType]: ToEntityMarshaller[A] = | |
Marshaller.oneOf(plainText, json) | |
def transformToPlainTextRequest(req: HttpRequest): HttpRequest = | |
req.uri.query().get("raw") match { | |
case None => req | |
case Some("true") => req.copy(headers = | |
req.headers.filter(_.name() != "Accept") :+ RawHeader("Accept", "text/plain")) | |
case Some("false") | _ => req | |
} | |
val route = | |
path("hello") { | |
get { | |
mapRequest(transformToPlainTextRequest) { | |
complete { | |
SomeClass("hello") | |
} | |
} | |
} | |
} | |
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) | |
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...") | |
StdIn.readLine() // let it run until user presses return | |
bindingFuture | |
.flatMap(_.unbind()) // trigger unbinding from the port | |
.onComplete(_ => system.terminate()) // and shutdown when done | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment