Skip to content

Instantly share code, notes, and snippets.

@dsugden
Last active August 29, 2015 14:12
Show Gist options
  • Save dsugden/54ca1ace2503c80fa792 to your computer and use it in GitHub Desktop.
Save dsugden/54ca1ace2503c80fa792 to your computer and use it in GitHub Desktop.
upickle akka-http
import akka.http.marshalling._
import akka.http.model._
import akka.http.unmarshalling.{FromResponseUnmarshaller, FromRequestUnmarshaller, Unmarshaller}
import akka.stream.FlowMaterializer
import upickle.{Writer, Reader}
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.implicitConversions
trait BaseUPickleSupport {
implicit def upickleFromRequestUnmarshaller[T: Reader](implicit fm:FlowMaterializer, ex:ExecutionContext):FromRequestUnmarshaller[T] =
new Unmarshaller[HttpRequest,T] {
def apply(req: HttpRequest): Future[T] = {
req.entity.withContentType(ContentTypes.`application/json`).toStrict(1.second)
.map(_.data.toArray).map(x => upickle.read[T](new String(x)))
}
}
implicit def upickleFromResponseUnmarshaller[T: Reader](implicit fm:FlowMaterializer, ex:ExecutionContext):FromResponseUnmarshaller[T] =
new Unmarshaller[HttpResponse,T] {
def apply(res: HttpResponse): Future[T] = {
res.entity.withContentType(ContentTypes.`application/json`).toStrict(1.second).map(_.data.toArray).map(x => upickle.read[T](new String(x)))
}
}
implicit def upickleToEntityMarshaller[T:Writer]:ToEntityMarshaller[T] =
Marshaller.withFixedCharset[T, MessageEntity](MediaTypes.`application/json`,HttpCharset.custom("*"))( tp =>
HttpEntity(upickle.write[T](tp)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment