How to get raw value of `content-type` header in Akka Http?

518 Views Asked by At

I am migrating from code spray (version: 1.3.4) to akka-http (version: 10.0.13).

We have an existing clients they send Content-Type like application/vnd.awesome.value; mykey="custom/custom"

Following code works fine in spray but in akka-http parameter (mykey) is stripped off

request.header[`Content-Type`].map { header =>
  // HERE PARAMS IS EMPTY MAP
  val myKeyValue = header.contentType.mediaType.params.get("mykey").map(_.replace("\"", ""))
  myKeyValue.flatMap(_.toMediaType).getOrElse(header.contentType.mediaType)
}.getOrElse(defaultMediaType)

StringToMediaTypeConversion.scala

val customMediaTypes: List[MediaType] = ???
implicit class StringToMediaType(private val str: String) extends AnyVal {
  private def parseMediaType(input: String): Option[MediaType] = MediaType.parse(input).fold(_ => None, Some(_))
  private def isSupportedType(mediaType: MediaType): Boolean = customMediaTypes.contains(mediaType)
  private def extractMediaTypeParamIfExists(mediaType: MediaType): Option[MediaType] = mediaType.params.get("mykey") match {
    case Some(value) => parseMediaType(value)
    case None        => Some(mediaType)
  }

  def toMediaType: Option[MediaType] = parseMediaType(str).flatMap(extractMediaTypeParamIfExists).filter(isSupportedType)

}

Following unit test is working is passing

val customMediaType: Option[MediaType] = """application/vnd.awesome.value; mykey="custom/custom""""".toMediaType
customMediaType should not be None
customMediaType.get.mainType shouldBe "custom"
customMediaType.get.subType shouldBe "custom"

Any help is appreciated.

How to extract raw value? or How to extract param value of media type?

1

There are 1 best solutions below

0
Seeta Ramayya Vadali On

I was registering custom media types as specified in the documentation, if I remove it I am seeing expected behaviour.