Skip to content

Instantly share code, notes, and snippets.

@andimiller
Created October 19, 2018 16:51
Show Gist options
  • Save andimiller/b2e32f8979b29cafa0eca6644f6884de to your computer and use it in GitHub Desktop.
Save andimiller/b2e32f8979b29cafa0eca6644f6884de to your computer and use it in GitHub Desktop.
sized decoder for http4s
case class Sized[T](bytes: Long, value: T)
object Sized {
implicit def sizedEntityDecoder[F[_] : FlatMap, T](implicit dec: EntityDecoder[F, T], F: Sync[F]): EntityDecoder[F, Sized[T]] =
new EntityDecoder[F, Sized[T]] {
override def decode(msg: Message[F], strict: Boolean): DecodeResult[F, Sized[T]] = {
EitherT(
for {
counter <- F.delay {
new LongAdder()
}
wrappedmsg <- F.delay {
msg.withEntity(msg.body.chunks.observe1(c => F.delay(counter.add(c.size.toLong))))
}
result <- dec.decode(wrappedmsg, strict).value
sum <- F.delay {
counter.sum()
}
} yield result.map(x => Sized(sum, x))
)
}
override def consumes: Set[MediaRange] = dec.consumes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment