Skip to content

Commit

Permalink
Fix accept header handling (#2391)
Browse files Browse the repository at this point in the history
* Fix accept header handling

* Fix test
  • Loading branch information
vigoo authored Aug 18, 2023
1 parent 676227f commit 33ed169
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,29 @@ object MediaTypeCodec {
def codecsFor(mediaType: Option[String], content: Chunk[BodyCodec[_]]): Map[String, MediaTypeCodec[_]] = {
mediaType match {
case Some(mt) =>
allByType.get(mt) match {
case Some(codec) => Map(mt -> codec.create(content))
case None =>
throw HttpCodecError.UnsupportedContentType(
s"""The Accept header mime type $mt is currently not supported.
|Supported mime types are: ${allByType.keys.mkString(", ")}""".stripMargin,
)
if (mt.contains('*')) {
MediaType.parseCustomMediaType(mt) match {
case Some(parsed) if parsed.mainType == "*" && parsed.subType == "*" =>
allByType.map { case (k, v) => k -> v.create(content) }
case Some(parsed) if parsed.subType == "*" =>
allByType.filter { case (k, _) => k.startsWith(parsed.mainType + "/") }.map { case (k, v) =>
k -> v.create(content)
}
case _ =>
throw HttpCodecError.UnsupportedContentType(
s"""The Accept header mime type $mt is currently not supported.
|Supported mime types are: ${allByType.keys.mkString(", ")}""".stripMargin,
)
}
} else {
allByType.get(mt) match {
case Some(codec) => Map(mt -> codec.create(content))
case None =>
throw HttpCodecError.UnsupportedContentType(
s"""The Accept header mime type $mt is currently not supported.
|Supported mime types are: ${allByType.keys.mkString(", ")}""".stripMargin,
)
}
}
case None => allByType.map { case (k, v) => k -> v.create(content) }
}
Expand Down
4 changes: 3 additions & 1 deletion zio-http/src/test/scala/zio/http/endpoint/EndpointSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ object EndpointSpec extends ZIOHttpSpec {

for {
response <- routes.toHttpApp.runZIO(
Request.get(URL.decode(s"/posts?id=$id").toOption.get),
Request
.get(URL.decode(s"/posts?id=$id").toOption.get)
.addHeader(Header.Accept(MediaType.text.`plain`)),
)
contentType = response.header(Header.ContentType)
} yield assertTrue(extractStatus(response).code == 200) &&
Expand Down

0 comments on commit 33ed169

Please sign in to comment.